Creating new GameObjects from script and want to Destroy() new objects when they are clicked on...

What is happening is that when I click on the newly formed objects/buttons it stops the entire process of creating them and does not Destroy() the object/button that I click on… I just want to Destroy the specific button that I click on even when the script is still creating new objects from the for loop:

public class CreateTenButtons : MonoBehaviour
{
int x;
int clicked;
public System.Random rnd = new System.Random();
private IEnumerator coroutine;

    void Start ()
    {
        coroutine = DoTenTimes(0.5f);
        StartCoroutine(coroutine);
    }
  

    IEnumerator DoTenTimes(float waitTime)
    {
        for (x = 0; x <= 10; x++)
     {

    yield return new WaitForSeconds(waitTime);
  

    GameObject mCanvas = GameObject.Find("Canvas");
    GameObject button = new GameObject();

    Instantiate(button);
  
    button.AddComponent<CanvasRenderer>();
    button.AddComponent<RectTransform>();
  
    Button mButton = button.AddComponent<Button>();
    Image mImage =  button.AddComponent<Image>();
 
  
    button.transform.position = new Vector3(rnd.Next(0, 800), rnd.Next(0, 600), 0);
    button.transform.SetParent(mCanvas.transform);
    // button.GetComponent<Button>().onClick.AddListener(DoThisWhenClicked);
    mButton.onClick.AddListener(DoThisWhenClicked);
  
    print("Cmoroutine ended " + x + "  " + clicked);
    }
    }

 
void DoThisWhenClicked()
{
  clicked++;
  Destroy(this);
}

Line 48 will destroy this script. I don’t think you want that.

Probably what you want is to pass the reference to mButton into DoThisWhenClicked().

NOTE: you will need to “Capture” the mButton variable into another local to do this, otherwise it will always Destroy the current value of mButton. For details read about C# variable capture, but something like:

{ var temp = mButton;
  mButton.onClick.AddListener( () => {
    DoThisWhenClicked( temp);
  });
}

Then make the DoThisWhenClicked() accept the button reference and destroy it.

Destroy(thePassedInButton.gameObject);

If you just destroy the Button, the GameObject it was on and all its children will remain.

That’s why generally you wanna destroy theButton.gameObject as I did above.

1 Like

Ok thank you, I will give it a go