I’m not sure what I am doing wrong here, as all references are set in the inspector. The coroutine starts and waits the correct time but, Its giving me this error at the if statement:
NullReferenceException: Object reference not set to an instance of an object
EnemySpawner+<SpawnCycle>d__6.MoveNext () (at Assets/Scripts/LevelElements/EnemySpawner.cs:23)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <1332c534a8a44623b2e5cc943a0b790e>:0)
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public bool canSpawn;
public GameObject enemyToSpawn;
public float spawnRate;
public int maxEnemies;
private List<GameObject> myEnemies;
void Start()
{
if (canSpawn)
{
StartCoroutine("SpawnCycle");
}
}
private IEnumerator SpawnCycle()
{
yield return new WaitForSeconds(spawnRate);
if (myEnemies.Count < maxEnemies && canSpawn)
{
GameObject newEnemy = Instantiate(enemyToSpawn, transform.position, transform.rotation);
myEnemies.Add(newEnemy);
Debug.Log("Spawned Enemy. My enemy count: " + myEnemies.Count + " out of " + maxEnemies);
StartCoroutine("SpawnCycle");
}
else
{
Debug.Log("Did not spawn enemy. My enemy count: " + myEnemies.Count + " out of " + maxEnemies);
StartCoroutine("SpawnCycle");
}
}
}
Help would be apricated