NullReferenceException for IEmunerator

Hello.

I’ve got an issue with my code. It relates to spawning enemies in a line. When I run the game, it spawns 1 enemy that doesn’t move, then stops and produces this error. I’ve looked around but I can’t find anything that would cause the NullReferenceException.

What should I do?

Thanks.

private IEnumerator EnemyWaveSpawner(WaveConfig wavConfig)
{
    for (int enemyCount = 0; enemyCount < wavConfig.GetNumberOfEnemies(); enemyCount++)
    {
        var newEnemy = Instantiate(wavConfig.GetEnemyPrefab(), wavConfig.GetWaypoints()[0].transform.position, Quaternion.identity);
        yield return new WaitForSeconds(wavConfig.GetTimeBetweenSpawns());
        newEnemy.GetComponent<EnemyPathway>().SetEnemyPath(wavConfig);
    }

}

The problem is the line `newEnemy.GetComponent().SetEnemyPath(wavConfig);

Hi,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring.

In newEnemy.GetComponent<EnemyPathway>().SetEnemyPath(wavConfig);, either newEnemy is null or GetComponent<EnemyPathway>() returns null. Log both values into your console to figure out where the issue might come from.

Here’s what I’ve found.

I added this code, modified from the Unity docs.

            if (newEnemy)
            {
                Debug.Log(newEnemy.name);
            }
            else
            {
                Debug.Log("No variable named newEnemy found.");


            if (wavConfig)
            {
                 Debug.Log(wavConfig.name);
            }
            else
            {
                 Debug.Log("No WaveConfig named wavConfig found");
            }

I added it before the yield command.

This is what I got when running the game.

All 5 enemies are spawning, but not moving.

Did you manage to fix the NullReferenceException error?

If the enemies are not moving, please share the code you use for their movement. Have you already compared your code to the Lecture Project Changes which can be found in the Resources of this lecture?

I’ve not yet fixed it and I’ve also not checked the code to the Project Changes.

This is the code for “EnemyPathway.cs.”

{
    WaveConfig waveConfig;
    List<Transform> waypoints;
    int waypointIndex = 0;
    // Start is called before the first frame update
    void Start()
    {
        waypoints = waveConfig.GetWaypoints();
        transform.position = waypoints[waypointIndex].transform.position; 
    }

    // Update is called once per frame
    void Update()
    {
        movement();
    }

    public void SetEnemyPath(WaveConfig waveConfig)
    {
        this.waveConfig = waveConfig;
    }

    private void movement()
    {
        if (waypointIndex <= waypoints.Count - 1)
        {
            var targetPos = waypoints[waypointIndex].transform.position;
            var movementThisFrame = waveConfig.GetMoveSpeed() * Time.deltaTime;
            transform.position = Vector2.MoveTowards(transform.position, targetPos, movementThisFrame);
            if (transform.position == targetPos)
            {
                waypointIndex++;
            }
        }

        else
        {
            Destroy(gameObject);
        }
    }
}

If it helps, this is the code for the WaveConfig scriptable object file.

{
    [SerializeField] GameObject enemyPrefab;
    [SerializeField] GameObject pathPrefab;
    [SerializeField] float timeBetweenSpawns = 0.5f;
    [SerializeField] float spawnRandomFactor = 0.4f;
    [SerializeField] int numberOfEnemies = 5;
    [SerializeField] float moveSpeed = 2f;


    public GameObject GetEnemyPrefab()
    { 
        return enemyPrefab;
    }
    public List<Transform> GetWaypoints()
    {
        var waveWaypoints = new List<Transform>();
        foreach (Transform child in pathPrefab.transform)
        {
            waveWaypoints.Add(child);
        }
        return waveWaypoints;
    }
    public float GetTimeBetweenSpawns()
    {
        return timeBetweenSpawns;
    }
    public float GetSpawnRandomFactor()
    {
        return spawnRandomFactor;
    }
    public int GetNumberOfEnemies() { return numberOfEnemies; }
    public float GetMoveSpeed() { return moveSpeed; }

}

Test Vector3.MoveTowards instead of Vector2.MoveTowards.

It didn’t fix the issue.

Have you already rewatched the video at least one more time? Maybe a detail is missing in your project.

Also please compare your code to Rick’s and fix the NullReferenceException error. The error might be causing your problem.

Hello. I’ve just compared my code in GitHub but I couldn’t find anything useful. I did check my Unity project however and I’ve found that the enemy doesn’t come with any scripts when the game is launched.


I had a look at the video again and found that in Rick’s video, he had the enemy pathing script on his enemy, so I added that, but I still have an error.

l23: movement();
l33: if (waypointIndex <= waypoints.Count - 1)

I’ve decided to revert my project back to an earlier state by destroying the EnemySpawner script, and removing a few lines of code. It means I’ve completed up to lecture 98. I’ve tested it and the game now spawns an enemy that moves.

I will work with that but I will keep this open for now.

If the error message points/pointed to the line with waypoints, the value of that variable is/was probably null.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms