How would I destroy an instantioted object in C#?

I have an item that gets cloned into the player, I would like for it to get destroyed when I press q…

I can not find any way to do that. basically, I press q to load Item, I want to press q to destroy it.

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour 
{
	public GameObject prefab;
	GameObject clone;
	bool prefabExists = false;

	void Update()
	{
		if(Input.GetKeyDown (KeyCode.Q))
		{
			if(!prefabExists)
				clone = (GameObject)Instantiate (prefab, transform.position + (transform.forward * 3), Quaternion.identity);

			else
			{
				if(clone != null)
				{
					Destroy (clone.gameObject);
					clone = null;
				}
			}

			prefabExists = clone != null;
			print (prefabExists);
		}
	}
}

Destroy(InstantiatedGameObject);

PLACE THIS WHEREEVER IN THE CODE IT IS THAT YOU WANT TO DESTROY GAMEOBJECT AFTER IT`S BEEN INSTANTIATED (guessing after a collision, so maybe…)

void OnTriggerEnter(Collider col)
{

//in your player object`s inspector, select Player from the dropdown menu of "Tag" 
if(col.gameObject.tag == "Player")

{
Destroy(InstantiatedGameObject);

}
}

Bearing in mind you should have access to the gameobject you want to destroy

simplest form of getting this achieved, add a

public GameObject go

to your script and attach the gameobject you want to destroy through the inspector panel. Now in the

Destroy()

call specify the GameObject go like this

Destroy(go);

Hey Presto…a transferable script to any object that can be destroyed by colliding with it.
Hope that helps somewhat.
:slight_smile:

Gruffy 2013