NullReferenceException being thrown when I try to add a component to a dictionary
I have the following section of code from a MonoBehaviour
class in a voxel engine that I'm currently working on right now:
public void CreateChunk(Position chunkPosition)
{
GameObject newChunk = (GameObject)Instantiate(
this.ChunkPrefab,
new Vector3(chunkPosition.X, chunkPosition.Y, chunkPosition.Z),
Quaternion.identity
);
Debug.Log("New Chunk", newChunk);
Chunk newChunkComponent = newChunk.GetComponent<Chunk>();
newChunkComponent.ChunkPosition = chunkPosition;
newChunkComponent.ParentTerrainManager = this;
this._ChunksInMemory.Add(chunkPosition, newChunkComponent);
for(int x = 0; x < Chunk.GlobalChunkSize; x++)
{
for(int y = 0; y < Chunk.GlobalChunkSize; y++)
{
for(int z = 0; z < Chunk.GlobalChunkSize; z++)
{
newChunkComponent.CreateBlock(new Position(x, y, z), new Stone());
}
}
}
}
The Chunk
class is also a MonoBehaviour
class as well. I'm trying to instantiate a chunk prefab and then get the Chunk
component from the instantiated prefab. Unfortunately I get the following NullReferenceException
:
NullReferenceException: Object reference not set to an instance of an object
Voxel.Engine.TerrainManager.CreateChunk (Position chunkPosition) (at Assets/Source/Engine/TerrainManager.cs:99)
Voxel.Engine.TerrainManager.Start () (at Assets/Source/Engine/TerrainManager.cs:132)
This is line 99:
this._ChunksInMemory.Add(chunkPosition, newChunkComponent);
The field this._ChunksInMemory
is simply a Dictionary<Position, Chunk>
containing all the currently loaded chunks.
I have done the following things so far:
I have confirmed that the
TerrainManager
MonoBehaviour
class (the one that contains the above section of code) does in fact have a chunk prefab assigned.I have confirmed that there is in fact a copy of the chunk prefab by looking at the hierarchy and calling
Debug.Log("Chunk created", newChunk)
.I have confirmed that the copy of the chunk prefab has a
Chunk
component attached to it.
At this point, I am clueless as to why my code isn't working. Just from looking at the code, it should work fine, but it doesn't. Does anyone know why this is happening?