Issue with my loop when I instantiate a prefab

Hello,

I’m new to Unity and I’m trying to work on a card project. I managed to have my prefab spawning in the scene with the correct image and text depending on the button clicked on. However, I ended up having two prefabs spawning at once. I managed to destroy one of them in the Update(), but the other one stays…

I’m pretty sure it’s because of the foreach, which must open my prefab for each one of my cards in the cardArray, but I don’t really know how to change it… For now it’s “fine”, because I’m only testing this with 2 cards, but I plan on having 44 cards at the end, so I would like to fix this issue soon.

This is the script with the loop :

[SerializeField] private GameObject cardParentUI;
    private bool cardParentOpen;

    [SerializeField] Cards[] cardArray;

    [SerializeField] GameObject cardPrefab;
    private GameObject clone;

    private Image iconImg;
    private Text descriptionTxt;

    private void Start()
    {  
        cardParentUI.SetActive(false);
        cardParentOpen = false;
    }

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.Escape))
        {
            cardParentUI.SetActive(false);
            cardParentOpen = false;
            Destroy(clone);
        }
    }

    public void SelectCard(int _id)
    {
        cardParentUI.SetActive(true);
        cardParentOpen = true;

        if (cardParentOpen)
        {
            for (int i = 0; i < cardArray.Length; i++)
            {
                if (cardArray[i].id == _id)
                {
                    foreach (Cards card in cardArray)
                    {
                        Debug.Log(cardArray[i].id + " / " + _id);
                        clone = Instantiate(cardPrefab, cardParentUI.transform);
                        Debug.Log("Instantiated");

                        descriptionTxt = cardPrefab.transform.Find("Description").GetComponentInChildren<Text>();
                        descriptionTxt.text = cardArray[i].description;
                        Debug.Log("Text set");

                        iconImg = cardPrefab.transform.Find("Icon").GetComponent<Image>();
                        iconImg.sprite = cardArray[i].icon;
                        Debug.Log("Image set");
                    }
                }
            }
        }
    }

Thank you for your help!

Looks like you’re only keeping one variable, clone.

This means card 1 goes in there, then card 2 goes in there and the reference to card 1 is lost. It’s still there in scene but your script has lost track of it.

You could keep a collection of them (perhaps with a List variable?)

You could also parent all of them to a single GameObject and destroy that parent GameObject when you want them all gone.