I'm getting a null reference exception error at the if statement in SpawnCycle() and I'm unsure why. All references are set in the inspector.

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");
        }

    }
}

Do you have myEnemies initialized somewhere? (using the ‘new’ command)

also how are able to compile private List myEnemies; without specifying the type? In your case, you would want List<GameObject> myEnemies;. And maybe in the Start() method have myEnemies = new List<GameObject>();. Which I assume is your problem.

I set my list from private to public and its working now. I don’t understand why though.