Setting variables on objects instantiated with array

Hello,
I’m trying to instantiate the entire deck of cards all at once here, then assign values to two (public) variables on the card as it is instantiated. I’m probably doing this a very computationally expensive way but that is ok, it’s a card game and this is only run once. Esentially unity is saying that it can’t find any definition of the variables on the gameobject. Now one of two things is happening here, I can’t assign values to variables on gameobjects instantiated with an array, or I have done something wrong. So do I need to have the object reference as an array, or have I missed a step, or something else?

Here is my code:

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour {

public GameObject cardPrefab;
public GameObject[] cards = new GameObject[10];
public int[,] cardrank = new int[4,18];


	// Use this for initialization
	void Start () {
		DefineDeck();
		CreateDeck();
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	
	void CreateDeck () {
		//Do this for every card
		for (int i = 0; i < 10; i++)
		{
			//create float versions of ints for the vector3
			float zero = 0f;
			float elevation = (float)i * 0.01f;
			//Instantiate the card in the deck
			cards[i] = Instantiate(cardPrefab, new Vector3(zero, elevation, zero), transform.rotation) as GameObject;
			for (int o = 0; o < 4; o++)
			{
				for (int p = 0; p < 18; p++)
				{
					if (cardrank[o,p] > 0)
					{
						cards[i].colour = o;
						cards[i].rank = p;
					}
					else
					{
						cardrank[o,p]--;
					}
				}
			}
		}
	}
	
	void DefineDeck () {
		//Define every card in the deck
		for (int o = 0; o < 4; o++) //Suit
		{
			for (int p = 0; p < 18; p++) //Rank
			{
				cardrank[o,p] = 2;
			}
		}
	}
	
	void Shuffle () {
	}
}

Thanks! :slight_smile:

You’re storing a reference to the new cards GameObject when you instantiate but GameObjects don’t have a colour or rank property. It’s likely one of the scripts attached to the object has these variables. To set those I think you need to do a GetComponent after you instantiate to get a reference to the newly created object’s script.

//Obtain reference to a script called "cardScript" which is a script on the instantiated object.
cards[i] = Instantiate(cardPrefab, new Vector3(zero, elevation, zero), transform.rotation) as GameObject;
cardScript thiscard = cards[i].GetComponent(cardScript);

then later on in your loop you set rank and colour like this

thiscard.colour=o;
thiscard.rank=p;

Edit: The above code is untested as I’m not near a Unity install to pre-test.

Of course… Thanks for the help!