This is an example from the book I'm reading. The section that is giving me trouble is the part where float 'otherScale' is declared. Originally, there is no initialization, but I added 1.5f just for fun. Surprisingly, otherScale is equal to 0 inside Update() ...why? Tried googling but not even sure how to search for an answer! Code (CSharp): using UnityEngine; using System.Collections; public class MoreScope : MonoBehaviour { OtherScope other; // Use this for initialization void Start () { other = (OtherScope)GameObject.FindObjectOfType (typeof(OtherScope)); Debug.Log (other.gameObject.name); } // Update is called once per frame public float otherScale = 1.5f; void Update () { other.Size = otherScale; } }
That mistake trips me up sometimes too, because it's easy to forget that the value of the variable may be different from the value typed in the code. To elaborate on his correct explanation, Unity automatically serializes all public variables, which means the value is set to what's typed in the Inspector. Initially this value will be what's typed in the code, but then if you change the code it won't change the Inspector again.
Thanks! So let's say I wanted the variable to have a initial value...I enter that in the Inspector rather than in the .cs file?
Use the Reset() method to define any default values for your scripts. You can reset scripts using the gear icon in the inspector and hitting the Reset field. Any new scripts automatically run Reset() one time when added to the Inspector.
You can specify an initial value when you write the variable the first time, and it will get used the first time. It just gets ignored any time after that; so type whatever you want for the new initial value (that will be used next time you add this script to a new object) but you also need to change the value in the Inspector on the existing object.
Just to add, you can also use HideInInspector if you want something to remain public but don't want it to appear in the editor.
Actually, Unity will still serialize that variable. The difference is really subtle and obscure, but you want NonSerialized As long as we're bringing up these serializable attributes, lately I've been using private fields with SerializeField rather than public fields when I want to link objects in the Inspector. The purpose of the variable is clearer at glance.