Instantiated Object sometimes gives NullReference but sometimes not

Viewed 35

So i am trying to make a simple gameobject saving system in Unity.

Whenever i place an cube i enter it in a GameObject called currentCube

GameObject currentCube = new GameObject();
currentCube = Instantiate(CubeBlue, placeLocation, new Quaternion());

This places my cube all good and well. Then just for debugging i check if the currentCube actually has the just placed Cube

print(currentCube.transform.position);

This does indeed give the location of my newly placed Cube. But then i try to add the cube to a List (also tried with an array)

cubes.Add(currentCube);

But then i get a NullReferenceException

NullReferenceException: Object reference not set to an instance of an object

And then with the Script filename and the location line of where i put the "cubes.Add(currentCube;)"

EDIT:

Also in my part above the void start i have stated private List<GameObject> cubes;

1 Answers

Looks like your List is not getting Initialized. Try

private List<GameObject> cubes = new List<GameObject>();
Related