Deleting a GameObject

This question seem to get asked a lot, which makes it slightly more embarrassing that I can’t get it to work!

I am trying to delete an Instantiated prefab that a user selects, I’ve checked through loads of questions on this very subject, but using Destroy doesn’t seem to work :confused:

//class level variable to store the object the user has selected
private GameObject selectedItem;

...

public void OnGUI (){		
	//if delete button is pressed
	if (GUI.Button(...))
	{			
		Destroy (selectedItem);    
	}    		
}

...

//use Raycast to detect the GameObject the user has touched 
//this is called from within Update() stack
if (Physics.Raycast(cursorRay, out hit, Mathf.Infinity, this.layerMask)){
	switch (hit.transform.tag) {
		case "tag":												
			selectedItem = hit.transform.gameObject;
                        break;

As far as I can tell, it sets the GameObject fine (it changes its color in other parts of the code), but the Destroy will not get rid of it!

Has anyone got any ideas? I know this isn’t much code to go by, but if you need more info/code let me know!

Cheers,

Dave McB

Like sdgd, I would say, first make your GO public so you can check in the inspector if it’s well set and if it corresponds to the right GO in the scene.
Next you can try other function like DestroyImmediate.
You can also check if there is no error in the debug.

The cause that came up to my mind is that this GO is actually being destroyed but another Raycast (because it’s being called in Update()) assigns this GO again and again (line 21 in your code). Please, check also if in other places in your code, you don’t reinitialize this GO.