I'm trying to assign colors to a array of buttons randomly using an array of colors, but it doesn't work. I seem to be getting a NullReferenceException for my foreachloop but I don't know why that is. For those who wish to know I'm trying to make a simple match three game for an assignment and I have to use UI, I can't use GameObjects, and I want to use the different color buttons for the objects in the game.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class match : MonoBehaviour {
public float time = 30.0f;
public float _score;
public GameObject pausePanel;
private Color[] colors;
//public Button[] buttons;
private Image[] image;
public Image im1;
public Image im2;
public Image im3;
public Image im4;
public Image im5;
public Image im6;
public Image im7;
public Image im8;
public Image im9;
public Image im10;
public Image im11;
public Image im12;
public Image im13;
public Image im14;
public Image im15;
public Image im16;
// Use this for initialization
void Start () {
_score = 0.0f;
colors = new Color[3];
//buttons = new Button[16];
image = new Image[16];
//colors [0] = Color.red;
//colors [1] = Color.blue;
//colors [2] = Color.green;
colors [0] = GetComponent<UnityEngine.UI.Image>().color = Color.red;
colors [1] = GetComponent<UnityEngine.UI.Image>().color = Color.blue;
colors [2] = GetComponent<UnityEngine.UI.Image>().color = Color.green;
image [0] = im1;
image [1] = im2;
image [2] = im3;
image [3] = im4;
image [4] = im5;
image [5] = im6;
image [6] = im7;
image [7] = im8;
image [8] = im9;
image [9] = im10;
image [10] = im11;
image [11] = im12;
image [12] = im13;
image [13] = im14;
image [14] = im15;
image [15] = im16;
}
// Update is called once per frame
void Update () {
time -= Time.deltaTime;
if (time <= 0) {
time = 0.0f;
}
if (time == 0 && _score == 0) {
pausePanel.SetActive (true);
}
AssignColor ();
}
void OnGUI()
{
GUI.Box (new Rect (10, 10, 30, 20), "" + time.ToString ("0"));
GUI.Box (new Rect (85, 410, 30, 20), "" + _score.ToString ("0"));
}
void AssignColor()
{
Debug.Log("Sup");
int colornum = Random.Range (0, colors.Length);
foreach (Image i in image) {
if(i.color == Color.white){
i.color = colors[colornum];
}
}
}