For example, if I initialize a variable globally, it would look like this:
public class ExampleOne : MonoBehaviour
{
public float x = 10.0f;
void Start()
{}
void Update()
{}
}
But if I initialize a variable in the Start() function, it would be like this:
public class ExampleTwo : MonoBehaviour
{
public float x;
void Start()
{
x = 10.0f;
}
void Update()
{}
}
Is there any difference between these two? Because I played around a bit and I noticed that if I initialize a variable to 10 globally, once I enter play mode, the said variable doesn’t start off with the value 10 in the first frame.
But if I initialize the variable in the Start() function instead, the variable starts off with the value 10 right from the first frame once I enter play mode.
Any idea why this is the case? Are the statements in Start() functions somehow prioritized over global statements?
if you initialize global float a = 10; then it is initialized before awake(). Difference is if you want to get component then difference is betwen awake() start() onenable etc… because awake is before start and onenable.
TheSaviour, you do not create Awake, Enable, and start. they are names of time instances. your Update function is called x FPS. even if you did not have an update function, your game would still run at x FPS.
if you have a function Start() in your script than it is called a short time after your game begins. if you have an Awake() function than it will be called at an even shorter time after your game begins. there for, it is safer.
if a different script in your game is running and that script has
void Awake()
{
x++;
}
then you will get an error because x is being set in the Start() function and start function is called after Awake().
When you create a member variable in your Monobehavior class
public int a=1;
The value 1 will be assigned to integer “a” when the object is INSTANTIATED (created / put in the scene). The game need not even be launched (played) for this value to be assigned (unlike Start). As soon as your behavior is put on an object, in the editor, this value will be assigned.
Once the object is instantiated, the value is saved, by unity serializing the Monobehavior object and saving it with the scene. When the scene is re-loaded, this serialized value will be re-assigned to the variable. If the scene is loaded becaue the game has just been started, Start() will be called AFTER the serialized values have been reassigned.
You can optionally use the Reset() function, to assign these values (what I would recommend). This also works in the editor, and does not require the game actually be running. This way when you select “reset” from the object’s editor menu, the object ACTS like it has just-now been instantiated.