-2

I've got a GameObject that is being instantiated:

var face = Instantiate(waveConfigs[waveNumber].getFacePrefab(), waypoint.position, Quaternion.identity, FindObjectOfType<Canvas>().transform);

Debug.Log(face, this);
faces.Add(face);

faces is declared above like this:

List<GameObject> faces;

The object gets instantiated, the DebugLog is follows:

Smile(Clone) (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)
FaceSpawner:SpawnFaces(Int32) (at Assets/Scripts/FaceSpawner.cs:30)
FaceSpawner:Start() (at Assets/Scripts/FaceSpawner.cs:16)

(Which is the Debug.Log(face, this);)

And then straight after that, when I call faces.Add():

NullReferenceException: Object reference not set to an instance of an object
FaceSpawner.SpawnFaces (System.Int32 waveNumber) (at Assets/Scripts/FaceSpawner.cs:31)
FaceSpawner.Start () (at Assets/Scripts/FaceSpawner.cs:16)

I dont get it, I've literally just assigned this variable, its worked, it appears on the canvas, I can log it out the debuglog, and then when I try and add it to a List I get a NullReference. What is going on here?

Chud37
  • 4,278
  • 12
  • 50
  • 98
  • You assign `face` not `faces` – JSteward Feb 24 '20 at 22:01
  • 1
    `List faces;` is a deceleration but *not* an assignment which means that `faces` does not point to an object in memory so it returns `null`. You have to assign it to a new or existing instance of an `List` if you want to use it. – Igor Feb 24 '20 at 22:05

1 Answers1

1

Have your faces container been initialized likewise List<GameObject> faces = new List<GameObject>()?

The thing is you're trying to Add to the container which hasn't been created, that is for which memory hasn't been allocated yet and for which its constructors hasn't been called. So basically you're trying to call function Add on non existent object.

Eric
  • 1,308
  • 12
  • 29
  • In the declarations I just have `List faces;` - do i need to be more specific? – Chud37 Feb 24 '20 at 22:05
  • Yes you have to allocate the memory for your `faces` container first, just as I pointed out in the answer – Eric Feb 24 '20 at 22:05
  • Thanks. It didnt occur to me that `faces` was the problem, I thought it was `face`. I'll mark your answer as correct! – Chud37 Feb 24 '20 at 22:07