I’m trying to add instantiated prefab to an array from another instantiated prefab
A world manager instantiates chunks and tiles within those chunks. Both worldmanager, chunks and tiles are GameObjects with scripts attached:
Chunk.cs
using UnityEngine;
using System.Collections;
public class Chunk : MonoBehaviour {
public WorldPos worldpos;
public GameObject[,] tiles;
void Start () {
tiles = new GameObject[16, 16];
}
}
WorldManager.cs
public void CreateChunk(int chunkx, int chunky)
{
WorldPos worldPos = new WorldPos (chunkx, chunky);
GameObject newChunkObject = Instantiate(
chunkPrefab, new Vector3(worldPos.x, worldPos.y, 0),
Quaternion.Euler(Vector3.zero)
) as GameObject;
Chunk newChunk = newChunkObject.GetComponent<Chunk>();
newChunk.worldpos = worldPos;
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 16; y++)
{
newChunk.tiles[x,y] = (GameObject)Instantiate(tilePrefab, new Vector3(newChunkObject.transform.position.x + x, newChunkObject.transform.position.y + y, 0), Quaternion.Euler(Vector3.zero));
}
}
}
When I try to set newChunk.tiles[x,y] it gives me a
NullReferenceException: A null value was found where an object instance was required.
Does anyone have any info on how to resolve this and make sure the array doesn’t raise that exception anymore when indexed? I thought this was possible because I initialized the array in the Start function of the chunk.
Is it because I’m declaring a Chunk variable and then get the script from that using getComponent? The Chunk.cs inherits from MonoBehavior but I wonder why Unity would still let me do that then?