Obtaining the Variable of a Prefab in an array.

Hi Guys,

Still trying to make this Blackjack game, I’ve gotten my cards to spawn upon a keypress, but what I want to do is grab the variable of the card prefabs which are being spawned and placed in an array.

Here is the code:

(Box Controller Script)

public GameObject[] cardsInBox;
private Vector3 cardPosition = new Vector3 (.1f, .01f, -.1f);
public int boxTotal = 0;
public int cardCount = 0;
public GameObject card;

void Update ()
{
	if (Input.GetKeyDown(KeyCode.H))
	    {
		BoxHit();
		Debug.Log (boxTotal);
		}
}
	void BoxHit()
{
			cardsInBox[cardCount] = Instantiate(card, transform.position + cardPosition * cardCount, transform.rotation) as GameObject;
			cardsInBox[cardCount].name = "PlayerCard" + cardCount.ToString();
			boxTotal += cardsInBox[cardCount].GetComponent<Cards>().cardValue;
			Debug.Log(cardsInBox[cardCount].GetComponent<Cards>().cardValue);
			cardCount++;
}

Inside the GameObject card is where I attach the card prefab in the inspector.
When card is instantiated, it runs this script to determine its value.

    public int cardValue = 1;

void Start () 
{
	cardValue = (int)Random.Range (1,13);
}

At the moment, when I hit H, the card spawns fine, and each prefab within the cardsInBox array has it’s own value which I can see in the inspector, however boxTotal increments only by 1 and not the Spawns prefab variable, I suspect I’m simply grabbing the card Prefabs value before it is intantiated, but I don’t know how to access the variable of the prefab that has been spawned, any ideas?

If your are just instantiating it, it may not run its Start() method until after you check for the value of “cardValue” therefor giving it the default value. What you could do, that MIGHT work (I am not totally sure this is what is happening I could always be wrong lol) is instead of having it set its value in Start() of the cards own script, instead assign that value just after creation, and before using the value.

So this part:

   cardsInBox[cardCount] = Instantiate(card, transform.position + cardPosition * cardCount, transform.rotation) as GameObject;
         cardsInBox[cardCount].name = "PlayerCard" + cardCount.ToString();
         boxTotal += cardsInBox[cardCount].GetComponent<Cards>().cardValue;
         Debug.Log(cardsInBox[cardCount].GetComponent<Cards>().cardValue);
         cardCount++;

Would become:

       cardsInBox[cardCount] = Instantiate(card, transform.position + cardPosition * cardCount, transform.rotation) as GameObject;
cardsInBox[cardCount].GetComponent<Cards>().cardValue = (int)Random.Range (1,13);
             cardsInBox[cardCount].name = "PlayerCard" + cardCount.ToString();
             boxTotal += cardsInBox[cardCount].GetComponent<Cards>().cardValue;
             Debug.Log(cardsInBox[cardCount].GetComponent<Cards>().cardValue);
             cardCount++;

Good Luck!