how to destroy over populated gameObjects? (C#)

The player throws a fireball by pressing “F”. How do I destroy a fireball object instance if the fireball count is more than 4? I already made the ballCount int here:

int ballCount = GameObject.FindGameObjectsWithTag("fireBall").Length;

Now I need help finishing the script. How exactly would I write the function, if it starts with:

if(ballCount > 4)

Also, if it isn’t too much of a hassle, is there any way I can destroy the fireBall object after a certain period of time?

Firstly, I would advice you not to use the FindGameObjecsWithTag() to much. It’s can be expensive if used too much, and if you change the tag of your object, the code will be broken. You’d better store each of your fireball instance in an array you’ll maintain yourself, and then do what you want with it :slight_smile:

Concerning limited lifetime, the easiest thing to do would be to create a classe inheriting MonoBehaviour for your fireball with a limited lifetime and a time counter. Something like this :

using UnityEngine;
using System.Collections;

public class FireBall : MonoBehaviour {

	public float lifetime = 4f;
	
	float timeCount = 0f;
	
	// Update is called once per frame
	void Update () {
		timeCount += Time.deltaTime;
		if(timeCount > lifetime)
		{
			GameObject.Destroy(this.gameObject);	
		}
	}
}

Hope it helped in any way :slight_smile:

If you want to destroy the fireball after a certain amount of time, it’s very easy. The Destroy function has a second parameter where you can define a time delay.

using UnityEngine;
using System.Collections;

public class FireBall : MonoBehaviour
{
    public float lifetime = 4f;
    void Start ()
    {
        GameObject.Destroy(gameObject, lifetime);
    }
}

This will destroy the fireball after 4 seconds. If you really want to destroy the oldest fireball when you exceed the max-amount you can do it like this:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class FireBall : MonoBehaviour
{
    static List<GameObject> m_FireBalls = new List<GameObject>;
    static int m_MaxFireBalls = 4;
    public float lifetime = 4f;
    void OnEnable ()
    {
        if (m_FireBalls.Count > m_MaxFireBalls)
            Destroy(m_FireBalls[0]);
        m_FireBalls.Add(gameObject);
    }
    void OnDisable ()
    {
        m_FireBalls.Remove(gameObject);
    }
}

This will automatically register each fireball in the static list and if a new fireball detects there are already 4 others, it destroys the oldest in the list. Each fireball will remove itself when it’s destroyed, so the keeps the list up-to-date.

However, i would also use a max lifetime in addition (can be quite large > 10). Just to make sure a fireball doesn’t live forever.