Instantiate an object and destroy it after given time

Hi all,

I want to instantiate some gameobjects (let’s say lightning, explosions, etc) that will appear and last for some given time.

So far, I can instantiate and destroy the gameobject on the Start function but when I try to do the same on Update (that’s what I need) the scene hangs and never destroy the objects so it creates prefabs forever.

Here is the code:

using UnityEngine;
using System.Collections;

public class IntermittentShit : MonoBehaviour {
	
	public GameObject shitPrefab;
	public GameObject shitPosition;
	public float time; //the time to appear
	public float time2; // the time to destroy the object

	IEnumerator LightningMethod(){

		yield return new WaitForSeconds(time);
		foreach (Transform child in transform) {
			GameObject enemy = Instantiate (shitPrefab, child.transform.position, child.transform.rotation) as GameObject;
			enemy.transform.parent = child;
			yield return new WaitForSeconds(time2);
			Destroy (gameObject);
		}
	}
	
	void Start () {

	}
	void Update() {
		StartCoroutine(LightningMethod());
	}
}

What am I doing wrong? Do you know any other method to create intermittent objects (light, lightning, smoke, etc) better than this?

Thank you very much guys.

Regards,

I know it is little bit late answer but the easiest way I gues;

GameObject go = Instantiate(myObj,pos,rot) as GameObject;
Destroy(go, 5); //Destroy after 5 seconds.

You’re calling LightningMethod at every frame through the Update event right now. You need to create a global boolean that is trued when coroutine is called and falsed when it’s finished running. Just make sure you can call it again only when it is false ie when it’s finished running.