- Home /
Problem setting up instantiated card id
Hello!
I have a silly problem - I'm trying to create a simple deck of cards. I have a GameObject deck which has a script attached:
public List<string> cards;
public GameObject emptyCard;
public string activeCard;
// Use this for initialization
void Start () {
cards = new List<string>();
cards.Add("2club");
cards.Add("3club");
cards.Add("4club");
cards.Add("2hearts");
cards.Add("3hearts");
cards.Add("4hearts");
}
// Update is called once per frame
void DrawCard () {
var randomNumber = Random.Range(0,cards.Count);
print ("random number: "+randomNumber);
var drawnCard = cards[randomNumber];
activeCard = drawnCard;
print("drawn card: "+activeCard);
Instantiate(emptyCard,new Vector3(0f,0f,0f),Quaternion.identity);
var spawnedCard = emptyCard.GetComponent<activeCard>();
spawnedCard.cardId = activeCard;
print ("card id set: "+spawnedCard.cardId);
RemoveFromDeck ();
}
void OnMouseDown (){
DrawCard();
}
void RemoveFromDeck (){
cards.Remove(activeCard);
print ("deleted: "+activeCard);
}
Then Ihave a prefab emptyCard, with script:
public class activeCard : MonoBehaviour {
public string cardId;
}
When I run scene, after i click on deck I get a weird results: variable cardId of instantiated card is different then variable activeCard set in deck's script. Do you have any ideas of what I'm doing wrong? Much thanks for help!
Answer by KellyThomas · Jan 12, 2014 at 04:44 PM
You have a public variable emptyCard (that has a prefab attached?)
You then instantiate a clone of this prefab but don't keep a reference to the clone.
You then set the
cardID
of the prefab
Try swaping in these line:
GameObject clonedCard = Instantiate(emptyCard,new Vector3(0f,0f,0f),Quaternion.identity) as GameObject;
var spawnedCard = clonedCard.GetComponent<activeCard>();
Thank you very much, that helped. I had to add "as GameObject" to make it work.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Stack Card 0 Answers
How do I move/copy functions from one script to another while playing? 1 Answer
Store card data 1 Answer