I'm creating a 2D brick breaking game in unity 4.3. I want all of my bricks to be different colours for each game, so I've created a C# script to assign random colours to each brick when the game starts, about every half-second to "Make it look cooler." However, when I run my game I get the following error:
NullReferenceException: Object reference not set to an instance of an object
BlockInitialiser+<blockColour>c__Iterator0.MoveNext () (at Assets/Scripts /BlockInitialiser.cs:16)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
BlockInitialiser:Start() (at Assets/Scripts/BlockInitialiser.cs:9)
Here is my code:
using UnityEngine;
using System.Collections;
public class BlockInitialiser : MonoBehaviour {
GameObject[] blocks;
// Use this for initialization
void Start ()
{
StartCoroutine (blockColour ());
blocks = GameObject.FindGameObjectsWithTag ("Brick");
blocks = new GameObject[40];
}
IEnumerator blockColour()
{
foreach (GameObject block in blocks)
block.renderer.material.color = new Color(Random.value,Random.value,Random.value);
yield return new WaitForSeconds (0.5F);
}
PS I'm a noob both with C# and Unity, so this is probably a really easy fix, but despite reading through loads of other questions, I just can't get it right. Thanks in advance, guys.