- Home /
How do I add new instances of a object into a list?
I've seen similar problems but I still can't figure it out. What I'm trying to do is create a list of Cards from a non-standard deck and add them all into a deck class. This is just part of the method I'm working on for creating the deck but you should get the gist of the method.
List<Card> cards = new List<Card>();
public void createOriginalDeck ()
{
int [] cardValuesTemp = {3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5};
//Red cards
for (int i=0; i<12; i++) {
Card temp = new Card(ColorSuit.Red, BidAction.None, cardValuesTemp[i]);
cards.Add(temp);
}
}
But I got an error about using the word new. I saw that I could get rid of the MonoBehaviour inheritance but I think I need it. So I Changed the code to
List<Card> cards = new List<Card>();
public GameObject deck;
Card cardModel;
void Awake(){
cardModel = deck.GetComponent<Card>();
}
public void createOriginalDeck ()
{
int [] cardValuesTemp = {3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5};
//Red cards
for (int i=0; i<12; i++) {
Card temp = deck.AddComponent<Card>();
temp.color = ColorSuit.Red;
temp.bidAction = BidAction.None;
temp.cardValues = cardValuesTemp[i];
cards.Add (temp);
}
}
This seems to work except that I am pretty sure it isn't right. For one I never use the cardModel, but it didn't work unless I did it so I just don't understand. When I run it in unity I get the deck to appear Correctly but each clone card has around 50 components, one for every card in the deck listing its attributes (ColorSuit, BidAction, and value) instead of just one component listing its own attributes. There has to be a better method than addComponent for this right?
Your Card class really shouldn't be a child of $$anonymous$$onoBehaivior. For what do you need that relation?
Answer by gRntaus · May 08, 2016 at 02:09 PM
The MonoBehaviour
is only useful if you need to attach that script to a GameObject
at any point, otherwise it might as well just be a normal class without the MonoBehaviour
inheritance.
If you know that you need to add the script to a GameObject
at some point (or it is already attached to one) then you need to instead use Card card = GameObject.Instantiate(yourCardPrefab);
.
More info on Instantiate
can be found here