-2
\$\begingroup\$

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.

\$\endgroup\$
1

2 Answers 2

1
\$\begingroup\$

Change this:

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

To this:

blocks = GameObject.FindGameObjectsWithTag("Brick");
StartCoroutine(blockColour()); 
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .