NullReferenceException after unserializing WaveConfig

Hi, I have reached video 100 (hooray.png) in Rick’s 2D Udemy course, and got the NullReferenceException bug after removing [SerializeField] from the waveConfig parameter in the enemy path-finding script.
After looking around a bit and trying to find the problem with Debug.Log I got this:weird_bug
If I’m not wrong, this should mean that the SetWave() function is getting executed a bit too late, but putting the spawner script’s coroutine in Awake() instead of Start() didn’t get rid of the bug, and I can’t set it earlier without some variable not working. Does anybody know of a way to fix this? Thanks.

Code (some variables’ names are different):

public class EnemyPathfinder : MonoBehaviour
{
    EnemyWave waveConfig; //most likely the problem
    List<Transform> waypoints;
    int pointNum = 0;

    private void Start()
    {
        Debug.Log(waveConfig);
        waypoints = waveConfig.GetWaypoints(); //an error on this line
        transform.position = waypoints[0].transform.position;
    }
    private void Update()
    {
        FindPath();
    }

    public void SetWave(EnemyWave waveConfig)
    {
        this.waveConfig = waveConfig;
    }

    private void FindPath()
    {
        if (pointNum <= waypoints.Count - 1) //a 2nd error on this line
        {
            var target = waypoints[pointNum].transform.position;
            var movement = waveConfig.MovementSpeed() * Time.deltaTime;

            transform.position = Vector2.MoveTowards(transform.position, target, movement);

            if (target == transform.position) pointNum++;
        }
        else pointNum = pointNum * 0 + 1;
    }
}

Try this: Comment out the Start() method. Change FindPath() to…

    private void FindPath()
    {
        if (waveConfig == null)
        {
              return;
        }
        else if (waypoints == null)
        {
             waypoints = waveConfig.GetWaypoints(); 
             transform.position = waypoints[0].transform.position;
        }

        if (pointNum <= waypoints.Count - 1)
        {
            var target = waypoints[pointNum].transform.position;
            var movement = waveConfig.MovementSpeed() * Time.deltaTime;

            transform.position = Vector2.MoveTowards(transform.position, target, movement);

            if (target == transform.position) pointNum++;
        }
        else pointNum = pointNum * 0 + 1;
    }
1 Like

It’s fixed now! Thanks a lot, Seth

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

Privacy & Terms