I am not sure why but this is throwing
NullReferenceException: Object reference not set to an instance of an object
GridSquareController.Update () (at Assets/Scripts/GridSquareController.cs:53)
Code:
for (int i = 0; i < numOfPrefabs; i++)
{
System.Random rnd = new System.Random();
int squareValue = rnd.Next(1, 6);
gridBehaviour = spawnedPrefabs[i].GetComponent<GridBehaviour>();
gridBehaviour.gridValue = squareValue;
Debug.Log(gridBehaviour.gridValue);
}
I am trying to set a value on the scripts of a series of prefabs I am also initializing in another part of this code.
But every time I press the key that activates this for loop it throws the same error.
Section where prefabs are initialized:
void SpawnPrefabs()
{
//will create as many prefabs as I specify in the numOfPrefabs variable
if (numOfPrefabs > 0)
{
for (int i = 0; i < numOfPrefabs; i++)
{
GameObject newSpawnedPrefab;
//instantiates a new prefab
newSpawnedPrefab = Instantiate(gridTilePrefab, new Vector3(i, 0, 0), Quaternion.identity);
//parents the new prefab to the transform of the current object (just parenting it really)
newSpawnedPrefab.transform.SetParent(transform);
//adding the prefab to the array
spawnedPrefabs.SetValue(newSpawnedPrefab, i);
}
}
}
Also here's the bit where I defined my variables
// the prefab I am instantiating into the gameworld
public GameObject gridTilePrefab;
public GridBehaviour gridBehaviour;
// an array containing all of the spawned prefabs
public GameObject[] spawnedPrefabs;
// the number of prefabs I want spawned calculated from the length of the array containing the prefabs
public int numOfPrefabs;
public bool Jeremy;