Is there a low performance lifetime limiter?

I’m looking for an efficient way to limit the lifetime of instantiated gameobjects which are atoms that disappears after a set amount of time so they don’t overload the game. There are going to be well over a hundred atoms, and I’m looking for a way to make them have a lifetime that won’t lag the game when I attach them on each atom.

I tested these 2 scripts to be attached on each atom, but they really wreck the fps when there are just 50 atoms in the scene. Any ideas?

var Seconds = 10;
 
function Update(){
    Destroy();
}
 
function Destroy(){
    yield WaitForSeconds(Seconds);
    Destroy(gameObject);
}

    var lifetime = 1.1;
 
    function Awake()
    {
        Destroy(gameObject, lifetime);
    }

Don’t instantiate or destroy them. Create all the atoms you will need at startup ( maybe using some yields in the Instantiate loop so it doesn’t lock up the game) and immediately set them inactive and put them in a List.< GameObject >.

Then, set them active again one by one as needed. Doing it this way will produce little or no lag.

Performance wise, you can use a a stack of GameObjects that grows as necessary and archives the atoms after their lifetime expires. Here’s a class that can do that for you:

public class AtomCreator : MonoBehaviour {
    public GameObject atomPrefab;
	
	private Stack<GameObject> atomStack = new Stack<GameObject>();
	
	// enables an atom from the stack, if available. Otherwise creates a new one.
	public GameObject CreateAtom(float lifetime) {
		GameObject atom;
		if (atomStack.Count > 0) {
			atom = atomStack.Pop();
			atom.SetActive(true);
		} else {
			atom = GameObject.Instantiate(atomPrefab) as GameObject;
		}
		
		// destroy atom after lifetime expires
		if (lifetime > 0) {
			StartCoroutine(DestroyAtom(atom, lifetime));
		}
		return atom;
	}
	
	// disables the atom and adds it to the stack
	public IEnumerator DestroyAtom(GameObject atom, float delay) {
		yield return new WaitForSeconds(delay);
		atom.SetActive(false);
		atomStack.Push(atom);
	}
}

Call CreateAtom() with the lifetime you want it to have. It will either create a new one or reuse one from the stack if avaialable, and will return the created object so you can further manipulate it (like setting it’s position after creation). It will also start the coroutine to deactivate it after its lifetime expires, so it will automatically be deactivated and added to the stack, for future use. This is done automatically as long as you provide a lifetime that is greater than 0.