I am trying to code a card game in unity and i have a list called ‘Deck’ from which i want to draw a random card and then remove that card from the Deck and move it to another list called ‘DiscardPile’.
The drawing and adding to the discard pile is working, but it won’t remove the card from the deck. Why?
I have these functions:
public GameObject DrawCard(List<GameObject> cards)
{
GameObject playerCard = Instantiate(cards[Random.Range(0, cards.Count)], new Vector3(0, 0, 0), Quaternion.identity);
playerCard.transform.SetParent(PlayerArea.transform, false);
return(playerCard);
}
public void StartCards()
{
for(var i = 0; i < 2; i++)
{
PickedCard = DrawCard(Deck);
Deck.Remove(PickedCard);
DiscardPile.Add(PickedCard);
Debug.Log(DiscardPile[i]);
Debug.Log(Deck[1]);
}
}
>Solution :
It is not removed because the playerCard you return from the DrawCard method is not the original instance contained in Deck but rather a copy instance of it.
I would probably rather already remove it within the DrawCard method itself like e.g.
public GameObject DrawCard(List<GameObject> cards)
{
if(cards.Count == 0) return null;
var index = Random.Range(0, cards.Count);
var playerCard = Instantiate(cards[index]);
playerCard.transform.SetParent(PlayerArea.transform, false);
cards.RemoveAt(index);
return(playerCard);
}
In general it is probably easier to not use GameObject in your deck setup but rather some ScriptableObject only holding the card information.
Then you’d use a single prefab for the card visuals and initialize it with the according information whenever it is spawned. This way you separate the application model (data) from the UI display logic, moving a step into the direction of a classic Model-View-Controller (MVC) or Model-View-Presenter (MVP) architecture