Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove the return of a function from a list

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]);
        }
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading