How do I destroy an instantiated game object when player leaves trigger area?

Hi guys,

I’ve set up an empty game object with a trigger and attached a script which spawns a clone of a prefab when the player enters the trigger area.

However although OnTriggerExit2D registers my player leaving the trigger area (checked with debug.log) it doesn’t destroy the instantiated game object.

Any ideas on a good way to go about this?

Take a look at the code somthing like this sould work in 2d as well

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public GameObject objectToDestroy;
    public Transform SpawnLocation;

    private GameObject gameobj;
	// Use this for initialization
	void Start () {
        gameobj = objectToDestroy;
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void OnTriggerEnter(Collider other)
    {
        if(other.name == "Player")
        {
           objectToDestroy = (GameObject)Instantiate(gameobj, new Vector3(SpawnLocation.position.x, SpawnLocation.position.y, SpawnLocation.position.z), Quaternion.identity);
            objectToDestroy.name = "test";
        }
        Debug.Log("Enterd  "+ other.name);
    }
    void OnTriggerExit(Collider other)
    {
        Destroy(objectToDestroy);
    }
}  

I store the game object in another gameobject incase you still want to spawn again on enter. If you want it gone from the game then Instantiate objectToDestroy insted of gameobj.
I am new at this so it’s probably better ways of doing this but you know hope it helps