- Home /
How to Destory a Gameobject in C# after 3 seconds?
I'm trying to destroy a explosion after three seconds but my method is not working. I make the explosion after I kill the enemy in the EnemyAI script. I find the script attached to the explosion and call the function in the script to destroy the game object.
EnemyAI Script
public class EnemyAI : MonoBehaviour {
public GameObject explosion;
void Death(){
Destroy (gameObject); //kill the enemy
Quaternion randomRotation = Quaternion.Euler(0f, 0f, Random.Range(0f, 360f));
Instantiate(explosion, transform.position, randomRotation);
explosion.gameObject.GetComponent<DestroyItems>().DestroyExplosion();
}
}
DestroyItems Script
public class DestroyItems : MonoBehaviour {
float lifetime = 3.0f;
public void DestroyExplosion ()
{ Destroy (gameObject, lifetime); }
}
There are no errors, but the explosion does not disappear. I get a warning saying to use DestroyImmediate(theObject, true) which I don't want to use because it will cause problems later with missing assets in game folder.
Please avoid using IEnumerator and Coroutine in your answers. I'm just looking for something simple and I don't need complex answers because I know there must be a easy way to do this. Thanks
Answer by Socterean · Jan 06, 2014 at 08:48 PM
using UnityEngine;
using System.Collections;
public class DestroyByTime : MonoBehaviour
{
public float lifetime;
void Start ()
{
Destroy (gameObject, lifetime);
}
}
This is what you need. For better understandig of how and why I suggest watching this video that will explain all you need to know to overcome youre problem:
NOTE: under the video you will see the script that I shown you here.
Answer by CraigCrawford · Jan 07, 2014 at 06:19 PM
Thanks Socterean this video is one of the best tutorials I have seen. I can actually learn from it because I don't get lost in unnecessary stuff that sometimes occurs in tutorials. I guess IEnumerator and Coroutine is not as complex as I thought well at least the way this video shows how to do it. Thanks Again!!
Your answer