setting and accessing variables from within multiple Start() methods

I’m assuming the issue is probably related to the execution order of things.

I have a script for example

public partial class TerrainStuff
{
    public class TerrainDisplacement : MonoBehaviour
    {
        private float _brushSize = 100f;
        public float brushSize
        {
            get
            {
                return _brushSize;
            }
            set
            {
                _brushSize = value;
                //do some other stuff
            }
        }
}

which is called on and stored in a static variable

public class MapManager : MonoBehaviour
{
    public static TerrainStuff.TerrainDisplacement terrainDisplacement;

    private void Start()
    {
        terrainDisplacement = gameObject.AddComponent<TerrainStuff.TerrainDisplacement>();
    }
}

and then i have another script where I am trying to access the “brushSize” via the static variable

public class FallingDebris : MonoBehaviour
{
    private void Start()
    {
        Debug.Log(MapManager.TerrainDisplacement.brushSize);
    }
}

When trying to run this, why do i get a NullReferenceException Error?

“Object reference not set to an instance of an object”

Am i misunderstanding the execution order or something? I’m trying to figure out how the Start() works a little more because moving the Debug.Log() to an update works absolutely fine.

Thanks in advance for any info

The Start methods on objects created at the same time can be called in any order. You could try changing MapMaanger’s Start method to Awake. Awake is called before Start.

thanks, I know it works from Awake() but i was wondering why it doesnt work from Start()

is there any way to control the order of execution within Start() methods?

just trying to learn and understand it a bit more that’s all :slight_smile:

There is, but it is better in the long run to try and architect your code so that execution order either doesn’t matter or is explicitly expressed in code.

In the specific use-case that you are running into – handling dependency injection – I will usually stick that into Awake, as it is more appropriate as in initialization step.

2 Likes