Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
    
Have a look at this question: stackoverflow.com/questions/7310454/… –  ChargingPun Apr 22 at 17:33

2 Answers 2

up vote 1 down vote accepted

Change this:

StartCoroutine(blockColour()); 
blocks = GameObject.FindGameObjectsWithTag("Brick"); 
blocks = new GameObject[40];

To this:

blocks = GameObject.FindGameObjectsWithTag("Brick");
StartCoroutine(blockColour()); 
share|improve this answer

You start your coroutine, which accesses the blocks array, BEFORE you fill it with GameObjects.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.