Removing specific items from list

Viewed 51

Hi im trying to figure out a way I can remove specific items from my list.

This is how I am currently drawing cards in my game:

public IEnumerator StartGame()
{
    for (int i = 0; i < 5; i++)
    {
        GameObject card = Instantiate(deck[deck.Count - 1], new Vector3(0, 0, 0), Quaternion.identity);
        card.transform.SetParent(hand.transform, false);
        hand.Add(deck[deck.Count - 1]);
        deck.RemoveAt(deck.Count - 1);
        yield return new WaitForSeconds(0.5f);
    }
    turnState = State.DrawPhase;
}

If possible I would like someway I could remove the gameobject from my "hand" list at the same time i remove it in the game. (If there is a better way to go about this I would like to know).

1 Answers

As far as I understand, you are looking for a method that removes an object from the list at the same time as destroying it. So you need an Extension class like the one below.

public static class ListExtension
{
    public static void DestroyAt(this List<GameObject> myList, int index)
    {
        GameObject.Destroy(myList[index]); // destroy object
        myList.RemoveAt(index); // remove it from list
    }
}
public void Start() => hand.DestroyAt(1); // for e.g
Related