C# - spawn limit not working properly.

I’m trying to put a limit to how many “objects” can spawn, using the amount specified as “maxEnemies”. But nothing whatsoever spawns, and I don’t know why.

using UnityEngine;
using System.Collections;

public class enemyAI : MonoBehaviour {


	private Vector2 spawnPosition;
	public GameObject[] objects;
	public float timer = 5f;
	public int maxEnemies = 10;

	// Use this for initialization
	void Start () 
	{

	}

	void Spawn() 
	{
		spawnPosition.x = Random.Range (-6.44f, 6.12f);
		spawnPosition.y = Random.Range (7.76f, 7.57f);
		Instantiate (objects[UnityEngine.Random.Range(0, objects.Length)], spawnPosition, Quaternion.identity);
	}
	
	// Update is called once per frame
	void Update ()
	{
		timer -= Time.deltaTime;
		if (timer <= 0f && objects.Length < maxEnemies) {
			Spawn ();
			timer = 2f;
		} 
		objects = GameObject.FindGameObjectsWithTag ("Enemy");
	}
	

}

I am fairly certain you have an issue with your objects. What you are trying to do makes little sense, and I think you probably have a logic issue here. At first, it appears that your objects is holding some prefabs for objects you want to randomly spawn, because of this line here:

 Instantiate (objects[UnityEngine.Random.Range(0, objects.Length)], spawnPosition, Quaternion.identity);

That line means that you must have some objects drug into the objects array in the inspector, or else you could not possibly instantiate anything, as it would null reference and spawn nothing (this is most likely your current problem). However, you then tell that same array to equal the GameObjects you find with the tag “Enemy”, which at that point could ever only possibly be the one you just spawned. This means the next time Spawn() ran you would just be spawning the exact same enemy over and over.

I think you want to have an objectsToSpawn for the random selection used in the Spawn() (that way you would randomly spawn one of those objects that you drug into the array via the inspector), and then the objects array is those objects you have spawned and limit the number of spawns with the objects.Length check.

The entire thing has some stink to it, so I would revisit the logic and make sure you understand what your code is doing. If need be, there are a lot of other answers out there for this same logic.

Here are a few of them for you. It actually looks like you are trying to take parts from a couple of these and put them together, but I would advise that you take some time and make sure you truly understand what your code is doing- it will pay off majorly in the long run!