i have an object that when it collides with an enemy after 3 seconds it destroys the enemy. the problem is that the collider only works inside OnTriggerStay (as far as i know) but the problem is that OnTriggerStay all happens within the span of 1 frame and I’m trying to use real time. this is my prototype code trying to make the idea work:
public class DestroyGhost : MonoBehaviour {
private float timer = 0;
public GameObject enemy;
void OnTriggerStay(Collider col) {
if (col.gameObject.tag == "Enemy") {
for (float timer = 0; timer < 3; timer += Time.deltaTime) {
Debug.Log(timer);
}
Destroy(enemy);
}
if (col.gameObject.tag != "Enemy") {
timer = 0;
}
}
If you want to destroy the enemy 3 seconds after the beginning of the collision, you can use:
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Enemy") {
Destroy (enemy, 3);
}
If you want to destroy the enemy after it collided during 3 seconds, you can use something like that :
float timer = 0;
void OnTriggerStay(Collider col) {
if (col.gameObject.tag == "Enemy") {
timer += Time.deltaTime);
}
}
void OnTriggerExit(Collider col) {
if (col.gameObject.tag == "Enemy") {
timer = 0;
}
}
void Update () {
if (timer > 3) { Destroy(enemy) }
}
Try this:
`
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Enemy")
Invoke("destroyEnemy", 3.0f);
}
private void destroyEnemy() {
// do something before destroy
Destroy(enemy);
}
or this:
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Enemy")
Destroy(enemy, 3.0f);
}
`