Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Who wins, the Inspector or Start function?

Discussion in 'Scripting' started by bugzilla, Jan 15, 2010.

  1. bugzilla

    bugzilla

    Joined:
    Dec 9, 2008
    Posts:
    196
    I've started running into a problem. I need to set some basic parameters, like hit points, mana,armor, game objects used as projectiles in the Start() function. But, when you drag an object into the scene, you can set variables manually in the Inspector panel. It would be great if I could drag in instances of the game creatures and just let the Start function take care of the variables, unless I override them manually using the Inspector.

    Problem is the stuff in the Inspector panel seems to be ignored. Any way to respect the variables assigned there within the script attached to an object?
     
  2. cdalexander

    cdalexander

    Joined:
    Nov 9, 2009
    Posts:
    73
    At the top of your script is usually where you define the global variabes such as:

    var varName01: GameObject;
    var varName02: float = 1.0;

    This puts two variables in your inspector that you will see named as: VarName01 and VarName02. I've placed a default value of 1.0 in the second variable, so in the inspector I will see 1.0 as the value. I can change the default through the inspector so it starts with another value. If I do, my default value will not be used on the gameobject that the changed value is on (but other gameobjects with this script will retain the default value unless you change them too).

    When the script executes the Start() function, those variables are already set to the defaults or whatever you assigned them through the inspector. So if you change the value within the Start function, they no longer equal there original value.

    So in order of execution:
    • Global variable equals the default value (if given)
      Override this by changing value in the inspector
      Override the default and inspector by changing it in Awake, Start, Update, or any other function in the script.
     
  3. bugzilla

    bugzilla

    Joined:
    Dec 9, 2008
    Posts:
    196
    Thanks Harmit. I had worked around it by using code like this in the Start() function

    {code}
    if(attacktype==""){attacktype="melee";}
    {/code}

    But your solution is better. Had no idea I could declare the default values for variables outside the Start() function. Hmmm...maybe the documentation should have cleared that up better.
     
  4. cdalexander

    cdalexander

    Joined:
    Nov 9, 2009
    Posts:
    73