Home > Net >  Difference between giving variables a value before or inside Start() method. C#
Difference between giving variables a value before or inside Start() method. C#

Time:11-27

Is there any fundamental difference between attributing a value to a variable before or inside the Start() method?

For clarity, I'm not talking about declaring variables but really just giving them values like, in this simple example:

using UnityEngine;

public class test : MonoBehaviour
{
    private float exampleFloat = 12.34f;

    private void Start()
    {
        //do stuff with exampleFloat
    }
}

versus this :

using UnityEngine;

public class test : MonoBehaviour
{
    private float exampleFloat;

    private void Start()
    {
       exampleFloat = 12.34f;
       //do stuff with exampleFloat
    }
}

CodePudding user response:

I don't know if Unity changes this at all, but at least in the pure C# world, the only difference can be shown with the question:

Do you intend to read from exampleFloat before calling Start()?

In the second example, where you just declare the variable, the variable will get assigned a value of 0 by default. If you try to read the variable before calling Start(), you won't see the value as 12.34.


There is a similar problem of "do I initialize variables inside or outside constructors?", but at least with using a constructor, you know the variable will have the target value before the object (class) is initialized.

CodePudding user response:

private float exampleFloat;

...declares the variable, and as it's a primitive type, sets it to its default value, in this case 0.

Therefore, if you access the variable before the Start method has run, it will be 0. If you access it inside Start, or after that has run, it will have the value 12.34.

By the way, this is a C# question, nothing to do with Unity.

  • Related