Delete a canvas

Hi, I want to delete a canvas on button click. That button is place inside the same canvas that i want to delete. I tried this scenario and unity crashes. What I want to achieve is to delete all the UI elements when i press a button.

Hi Umresh,

please use

public void ButtonClick()
{
		Destroy (GameObject.Find ("Canvas"));
}

i have executed the code using a canvas and a few Ui elements, it is not crashing but deleting the whole canvas…

You may try like this:

public void DeleteCurrentCanvas()
{
	Destroy (transform.gameObject.GetComponentInParent<Canvas>().gameObject);
}

Attach this script to button. I tested it with this hierarchy:

Canvas
.....Panel
..........Button   <----Attached script here 

This way you can work with more than one canvas present at a time and no need to define a tag or keep a reference of canvas.

Hope it helps!

How about rather than deleting just set them inactive by using Button’s onClick() select Editor and Runtime and Canvas underneath it and Gameobject.setactive .

Tag the canvas which you want to destroy.
Find the game object with tag, using FindGameObjectWithTag API.
Now destroy the Game Object.