So i want to limit the entitys in game to 50 but i don’t know how to.
Here’s my code if necessary:
//this is the var i used
private GameObject[] getCount;
//here i reference the var and make a new one using the first's length
void Start()
{
getCount = GameObject.FindGameObjectsWithTag("Enemy");
count = getCount.Length;
}
// i thinked that this if would limit but i don't know what to put
if (count > 50)
{
}
Im also new to Unity and it if is any other wrong thing say it too!
In whichever script you have that’s instantiating your enemies, make it keep track of how many have been instantiated, and prevent it from going over a maximum amount.
Example:
public class SpawnerExample : MonoBehaviour
{
public GameObject prefab;
public int maxSpawnCount = 50;
//The list of all the GameObjects we spawned.
private List<GameObject> instances = new List<GameObject>();
public void Spawn()
{
//Only spawn a new GameObject if we have less than maxSpawnCount instances.
if(instances.Count < maxSpawnCount)
{
GameObject instance = Instantiate(prefab);
instances.Add(instance);
}
}
}
You may also run into an edge case where if a spawned GameObject gets destroyed, its reference will become null in the instances List, but the Count of the List will not decrease, meaning you won’t be able to spawn any more instances even though you should be able to.
To fix that, you can update the List before every time you want to spawn a new instance to get rid of any null references:
public class SpawnerExample : MonoBehaviour
{
public GameObject prefab;
public int maxSpawnCount = 50;
//The list of all the GameObjects we spawned.
private List<GameObject> instances = new List<GameObject>();
public void Spawn()
{
//Remove all instances in the list that are null.
instances.RemoveAll(instance => instance == null);
//Only spawn a new GameObject if we have less than maxSpawnCount instances.
if(instances.Count < maxSpawnCount)
{
GameObject instance = Instantiate(prefab);
instances.Add(instance);
}
}
}