- Home /
Destroying a gameobject clone after a time
Here is my code for spawning multiple enemies forever. The level changes if they kill the player. How can i get it so that if the cloned objects collide with something then its deleted without causing errors i know to use something like this
using UnityEngine;
using System.Collections;
public class trigger_Destroy: MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "floor")
Debug.Log("destroying enemy...");
Destroy(gameObject);
}
}
But of course it wont work as the object the script is using is being deleted.. im stumped really. Not to sure on where to go. Any help is always appreciated.
var theObject:GameObject;
var maxPosx:float = 2.898618; // x axis
var minPosx:float = -1.89557; // x axis
var delay:float = 0.5; // delay each spawned item by 0.5
var maxPosy:float = 5.086665; // y axis
var minPosy:float = 5.086665; // y axis
function Start(){
StartCoroutine(spawn());
}
function spawn() : IEnumerator {
for (;;) {
yield WaitForSeconds(delay);
var theNewPos= new Vector3 (Random.Range(minPosx,maxPosx),Random.Range(minPosy,maxPosy),0);
var go : GameObject = Instantiate(theObject);
go.transform.position = theNewPos;
}
}
EDIT: What if i added
Destroy(theObject);
Which would destroy the cloned object that isnt needed? Im not on unity now but would this work in theory?
If you know of a way that i can edit this script to remove the spawned objects after a time i would appreciate it.
Are you using a prefab as the thing to copy with Instantiate()? It seems to me like you have a GameObject sitting in the scene, assigned as the thing to copy.
Answer by corriedotdev · Mar 24, 2014 at 09:15 PM
Once again i have answered my own question. I needed to destroy the clone, not the object itself.
in this case it would be
Destroy(go);
Answer by SkaredCreations · Mar 23, 2014 at 10:49 PM
Of course it's stopping the coroutine, because you're deleting the object itself that have attached the script. You should manage the spawn on a script attached to another object that is not going to be destroyed.