Null Reference Exception Laser Defender

Well on July 21st I ran into this problem & in attempts to solve it I had restarted the Laser Defender class twice already. Now I am stuck at the same exact place I was on July 21. Let me show you.


,…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyPathing : MonoBehaviour
{
[SerializeField] WaveConfig waveConfig;
List waypoints;
[SerializeField] float moveSpeed = 2f;

int waypointIndex = 0;
void Start()
{
    waypoints = waveConfig.GetWaypoints();
    transform.position = waypoints[waypointIndex].transform.position;
}

void Update()
{
    //EnemyPathing.Update () (at Assets/Scripts/EnemyPathing.cs:20) The Move(); is error

    Move();
}

private void Move()
{

    {
        // NullReferenceException: Object reference not set to an instance of an object
        // EnemyPathing.Move()(at Assets / Scripts / EnemyPathing.cs:28) The next line is error
        var targetPosition = waypoints[waypointIndex].transform.position;
        var movementThisFrame = moveSpeed * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);
        if (transform.position == targetPosition)

        {
            waypointIndex++;
            Debug.Log("Value of waypointIndex: " + waypointIndex);
            Debug.Log("Position of targetPosition: " + targetPosition);
        }
    
    else
    {
        Destroy(gameObject);
    }}
}

}
,…
For anyone who wants to see what I’ve already done & how I got here again.

1 Like

Might I ask you to upload a package of your project so I can test it out and see exactly what is going on? To do that go to Assets > Export Package, be sure that everything is selected, then upload it somewhere like Google Drive and post a link here.

Thank you. I’ll have to see if I can do that.

1 Like

https://drive.google.com/drive/folders/1ZbwddY-1JY-KEwS-Xo6YwYuAAa_qkDnc?usp=sharing

1 Like

Good news! I was able to download the package and the same error exists in my project so we can discard a Unity bug, bad news, we can discard a Unity bug which would have been kinda easy to solve, just change versions but that’s not the case.

I’ll be back as soon as I fix the error.

Problem solved!

ezgif-5-c6d6a5b64931

Your code works, well, not exactly, you did miss a couple of lines in EnemyPathing script.

Check the `Move` method here, you missed an 'if' statement.
    private void Move()
    {
        if (waypointIndex <= waypoints.Count - 1) //This line was missing.
        {
            var targetPosition = waypoints[waypointIndex].transform.position;
            var movementThisFrame = moveSpeed * Time.deltaTime;
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

            if (transform.position == targetPosition)
            {
                waypointIndex++;
                Debug.Log("Value of waypointIndex: " + waypointIndex);
                Debug.Log("Position of targetPosition: " + targetPosition);
            }
        }//This bracket was missing.
        else
        {
            Destroy(gameObject);
        } //You had an extra bracket here.
    }
}

But that had nothing to do with your issue, the problem was this:

Look at the settings of your enemy prefab, you didn’t save the changes you made to the object in the hierarchy, the ‘WaveConfig’ stayed at null, that’s why the enemy in the hierarchy was able to move but not the ones that were spawned after the game started.

Be sure to save the changes by selecting your object in the hierarchy, in the inspector click the Overrides drop-down menu and then click Apply All.

You can also modify the prefab directly if you click the arrow:
Arrow
This will open a special scene that allows you to modify the prefab directly.

One last thing, don’t forget to change the background’s or the Enemy’s order in layer, they are at the same order, meaning sometimes the enemy will be drawn on top of the background and others it will appear at the back.

Hope this helps!

Thank you. You’re right I didn’t hit apply all & I do see the if statement I didn’t copy & paste in for whatever reason (probably because after so long it’s really discouraging). So I also downloaded a different version of unity. I am getting the same results in both versions as I’ve been working on both of them.

  1. When I keep Rick’s destroy(gameObject) command the enemy teleports to waypoint (0) & then flashes a few times & disappears. This happens in less then a second. The enemy spawner will not spawn enemies when I use Rick’s destroy(gameObject).
  2. Everything will work if I remove Rick’s destroy(gameObject) command. Which would leave the enemy on the screen (which I assume is great for games like galaga not Laser Defenser). The enemies go from (0)-(3) & then stays on the screen piled on top of eachother.
    Same results in both version of unity.

Can you show me your DamageDealer and Enemy scripts, please.

,…using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyPathing : MonoBehaviour
{
[SerializeField] WaveConfig waveConfig;
List waypoints;
[SerializeField] float moveSpeed = 2f;

int waypointIndex = 0;
// Use this for initialization
void Start()
{   // the entire next line is error
    waypoints = waveConfig.GetWaypoints();
    transform.position = waypoints[waypointIndex].transform.position;
}

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

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

private void Move()
{   //the entire next line is error
    if (waypointIndex <= waypoints.Count - 1)

    {
        // NullReferenceException: Object reference not set to an instance of an object
        // EnemyPathing.Move()(at Assets / Scripts / EnemyPathing.cs:28) The next line is error
        var targetPosition = waypoints[waypointIndex].transform.position;
        var movementThisFrame = moveSpeed * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);
        if (transform.position == targetPosition)

        {
            waypointIndex++;
            Debug.Log("Value of waypointIndex: " + waypointIndex);
            Debug.Log("Position of targetPosition: " + targetPosition);
        }

} // causing the enemy to act funny so i muted it
/* else
{
Destroy(gameObject);
}*/
}
}
…,
,…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
[SerializeField] List waveConfigs;
int startingWave = 0;
// Start is called before the first frame update
void Start()
{
var currentWave = waveConfigs[startingWave];
//SAEW = SpawnAllEnemiesInWave
StartCoroutine(SAEW(currentWave));
}
private IEnumerator SAEW(WaveConfig waveConfig)
{
for (int enemyCount = 0; enemyCount < waveConfig.GetNumberOfEnemies(); enemyCount++)
{
Instantiate(waveConfig.GetEnemyPrefab(), waveConfig.GetWaypoints()[0].transform.position, Quaternion.identity);
yield return new WaitForSeconds(waveConfig.GetTimeBetweenSpawns());
}
}
}…,
I’m technically between lesson 96-99 right now so I don’t have a DamageDealer.cs yet.

,…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = “Enemy Wave Config”)]
public class WaveConfig : ScriptableObject
{

[SerializeField] GameObject enemyPrefab;
[SerializeField] GameObject pathPrefab;
[SerializeField] float timeBetweenSpawns = 0.5f;
[SerializeField] float spawnRandomFactor = 0.3f;
[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; }

}
…,

I was able to replicate the error, it has nothing to do with the code, I think the issue here is your prefabs, let’s go step by step.

  • Check your Enemy prefab and double click the WaveConfig it has attached.
  • Once open, check the WaveConfig settings, the time between spawn is probably set way too low. Check the other settings as well.
  • With the same WayConfig open double-click the Path Prefab.
  • Check how many waypoints does the Path Prefab has, it probably has only one, adjust that to have more.

This should solve your issue.

That was it. Slowing down the time speed. But here’s what I don’t get.
I did what you told me & thing were working. But now they’re not.


,…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyPathing : MonoBehaviour
{
WaveConfig waveConfig;
List waypoints;
int waypointIndex = 0;

// Use this for initialization
void Start()
{   // the entire next line is error
    waypoints = waveConfig.GetWaypoints();
    transform.position = waypoints[waypointIndex].transform.position;
}

// Update is called once per frame
void Update()
{//NullReferenceException: Object reference not set to an instance of an object
    Move();
}

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

private void Move()
{  //NullReferenceException: Object reference not set to an instance of an object
    if (waypointIndex <= waypoints.Count - 1)

    {
     
        var targetPosition = waypoints[waypointIndex].transform.position;
        var movementThisFrame = waveConfig.GetMoveSpeed() * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);
        if (transform.position == targetPosition)

        {
            waypointIndex++;
            Debug.Log("Value of waypointIndex: " + waypointIndex);
            Debug.Log("Position of targetPosition: " + targetPosition);
        }   

}
else
{
Destroy(gameObject);
}
}
}
…,
This solved the issue but for some reason it’s re-appeared. I’m currently on lesson 100.

I don’t see any issues with your code.

Check your Enemy Spawner game object, be sure that you assigned a WaveConfig object to the EnemySpawner newly exposed variable, if not, assign one. If that’s not the problem then the issue comes from the EnemySpawner script, try comparing it to Rick’s code and see if there’s something different.

So I copy/pasted Rick’s code as my Enemypathing.cs, WaveConfig.cs, & EnemySpawner.cs. These are my results. Now remember I’m using 2 different versions of unity doing this.


& obviously I still have these errors,
NullReferenceException: Object reference not set to an instance of an object
EnemyPathing.Move () (at Assets/Scripts/EnemyPathing.cs:32)
EnemyPathing.Update () (at Assets/Scripts/EnemyPathing.cs:22)

Thank you.

Where does SetWaveConfig() get called? The line which calls SetWaveConfig() is supposed to pass on a WaveConfig object. Maybe it passes on null.

From my perception of what Rick said it’s to set waveConfig to a variable class in which other scripts are based on. Or in plain English I don’t know. What I do know is.
I did what Yee told me to do & things worked when I hit play. But when I tried to complete the lesson something changed & IDK what it is.

The “Script Type not found” error is a little bit odd, to say the least, I’m not sure what might be causing this. I dig a little big around and in this case, this might be happening due to using multiple versions of Unity, I suggest you stop doing that and stick with one, as far as I’m aware there shouldn’t be an issue with you using a more recent version for the entire course.

Here I found a very nice thread that might help you solve this.

Thank you. I’m trying to do what they say. Most of the stuff I really don’t understand & is just extremely confusing. So what version of unity should I use? You said not to use 2020 & try something else so I am using 2021. Is it possible that Laser Defender is the problem & not unity, visual studios or my lack of knowledge but Laser Defender that is the problem?

I don’t remember saying not to use a specific version of Unity, I would never recommend that, use whichever you want as long as it is not a beta version, and be sure to not use the same project and change versions because that can cause a lot of unexpected issues. If you want to use multiple versions: copy-paste your project and then use different versions for each, but never upgrade or downgrade without having a backup because that can lead to losing all of our work.

I don’t think Laser Defender is the problem, if it were a lot of students would be stuck exactly were you are, and there aren’t, well… not exactly, I’ve seen a lot of students having problems with this specific part of the course, but after a while they are able to solve it without changing the code or doing anything fancy, it’s just that this part of the course can get a little too complex for some, and it is, you have to be fully aware of what the code is doing as well as keeping your prefabs updated and other stuff, it’s too much to handle if you are new to this.

What I would recommend is to take a break, you said you have been stuck here for a month or so, maybe what you need is to get your head clear.

Privacy & Terms