When do variables passed through the editor get initialized?

I have two scripts. I need to access a public GameObject array, which is located in the first script, but I get NullReferenceException error.

in the first class:

public GameObject[] discs;

in the second one:

void Start() {
  foreach (GameObject disc in GameController.Singleton.discs){
    myStack.Push(disc.GetComponent<Disc>().value);
  }
}

What can I do?

They get initialized before Awake() and Start() are called on the object they are on. If both classes are on objects that start in the scene then you should be good. If an object or class is created at runtime then they will be not be ready by the time the scene objects are initialized.

What is null, exactly? From your code any of the following being null could cause the exception:

  • discs
  • disc (one of the discs elements was empty in the editor)
  • GameController.Singleton (has the Singleton variable been set yet?)
  • disc.GetComponent() (maybe one of the discs elements is missing a Disc component)
  • myStack

By the way, if all discs must have a Disc component then you can change the declaration of discs to prevent dragging non-Disc-having GameObjects like so:

public Disc[] discs;

This also makes it so that you don’t need to call GetComponent to get the Disc component.