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?
What did you try that fail to work?
Post your script or else we can't really help you.
Answer by RustyCrow · Oct 20, 2015 at 09:40 PM
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
Thanks for the reply RustyCrow. This is pretty much what I have on my script but for some reason destroy does not get called.
public Transform Spawn;
GameObject SpawnClone;
void OnTriggerEnter2D (Collider2D col){
if (col.tag == "Player") {
SpawnClone = Instantiate (Spawn, transform.position, transform.rotation) as GameObject;
}
}
void OnTriggerExit2D(Collider2D col){
if (col.tag == "Player") {
Destroy (SpawnClone);
}
}
Change public Transform Spawn to public GameObject Spawn.
i had an error with interacting with transform to in 3d