- Home /
Destroying clone object in list does not remove the first one
Hi everyone,
I'm currently developing a system where Gameobjects are instantiated as Clones and added to a list. After the player makes a selection (each gameobject have a button attached to it) the onClick event will fire several Invokes and also remove the Gameobjects from the list and destroy the clones.
The issues I'm facing is that whenever the player has more than one Button to choose from two scenarios happens:
First scenario: player interact with the first button, all the Clones are destroyed and everything goes according to plan. Second scenario: player interact with the second (or any following) button, and all the Clones are destroyed, minus the first one.
I've tried several ways (Foreach loop, positive For loop, negative For loop) but nothing seems to work.
Here are the two main parts that regulates this code.
Instantiating the Objects and calling the Method:
public void ShowResponses(ui_Dialogue_Response[] ui_DR)
{
float responseBoxWidth = 0;
for (int i = 0; i < ui_DR.Length; i ++)
{
ui_Dialogue_Response Ui_D_R = ui_DR[i]; //This is a class that holds the various aspects of the response (sprite, name etc.)
int responseIndex = i;
GameObject responseButton = Instantiate(emojiResponseButton.gameObject, emojiContainer);
Button responseButtonButton = responseButton.GetComponent<Button>();
Sprite responseButtonSprite = responseButton.GetComponent<Sprite>();
responseButton.gameObject.SetActive(true);
responseButton.GetComponent<Image>().sprite = Ui_D_R.ResponseEmoji.sprite;
responseButton.GetComponent<Button>().onClick.AddListener(() => OnPickedResponse(Ui_D_R, responseIndex)); //This calls the method that will destroy the buttons and do some other stuff
tempResponseEmoji.Add(responseButton);
responseBoxWidth += emojiResponseButton.sizeDelta.x;
}
}
The method:
private void OnPickedResponse(ui_Dialogue_Response Ui_D_R, int responseIndex)
{
foreach (GameObject emoji in tempResponseEmoji)
{
Destroy(emoji);
}
tempResponseEmoji.Clear();
/*
for (int i = tempResponseEmoji.Count -1; i >=0 ; i--)
{
GameObject emojiClone = tempResponseEmoji[i];
Destroy(emojiClone);
//Destroy(tempResponseEmoji[i].gameObject, 0.1f);
tempResponseEmoji.RemoveAt(i);
}*/
}
As you can see I've tried a couple of ways to remove or destroy those gameobjects, but they do not work.
What am I doing wrong?
So you are cloning from scene game object and not instantiating from prefab? Are you sure that the 1st button you are pressing is not the "original" one? If so, then it will not be in the list and will not be destroyed.. of course this means that you must have some predefined button events to make the "original" 1st button work at all..
Your answer
![](https://koobas.hobune.stream/wayback/20220613050114im_/https://answers.unity.com/themes/thub/images/avi.jpg)