NullReferenceException: Object reference not set to an instance of an object, please help!!!

Can somebody please help me? I am new to coding and I am having the following issue: Newbie

NullReferenceException: Object reference not set to an instance of an object
Waves.Spawn () (at Assets/Waves.cs:61)
Waves.Update () (at Assets/Waves.cs:36)

here is my code, the issues are lines 61 and 36, the issues are listed above, can somebody please help walk me through this?

 using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waves : MonoBehaviour
{
    // Text to display what wave is next
    public TMPro.TextMeshPro wavesText;
    //The amount of enemies that each wave will increase by
    public int amountNewEnemysPerWave = 2;
    //The location coordinates for the enemies
    public Transform[] locationChords;
    //Locations where enemy will shoot.
    public int[] shootingLocations;
    //Counter keeping track of the amount of enemies previous wave.
    private int enemysLastWave = 1;
    //Spawn positions for the enemies.
    private Vector3 spawnPosition;
    //Current wave number
    private int currentWave = 0;
    //Timer to remove wave text
    private float textTimer = 0;

    private void Start()
    {
        Spawn();
    }
    void Update()
    {
        //Find one gameobject with the tag enemy in the scene
        var enemies = GameObject.FindGameObjectWithTag("Enemy");
        //If there are no enemies in the scene. Spawn new ones.
        if (enemies == null)
        {
            Spawn();[/B]
        }
        //remove the waves text when text timer is smaller than time since startup.
        if (textTimer < Time.realtimeSinceStartup)
        {
            wavesText.text = "";
        }
    }

    void Spawn()
    {
        //increase the current wave number
        currentWave++;
        //Set the correct number of enemies to the variable enemysLastWave. This is the same as writing enemysLastWave += amountNewEnemysPerWave;
        enemysLastWave = enemysLastWave + amountNewEnemysPerWave;
        //Loop to instansiate new enemies. run the loop for as many enemies there where last wave + as many new ones we add every wave.
        for (int i = enemysLastWave; i < enemysLastWave + amountNewEnemysPerWave; i++)
        {
            //Set a random spawn position of the enemy.
            spawnPosition.x = UnityEngine.Random.Range(-90, 90);
            spawnPosition.y = UnityEngine.Random.Range(-10, -70);
            spawnPosition.z = UnityEngine.Random.Range(80, 150);
            //Load a new Enemy from the enemy prefab in the Resource folder. It has to be in the folder called Resource.
            var enemy = Resources.Load<Enemy1>("Enemy");
            //Get a random set of locations that the enemy will travel between.
        enemy.locationCords = GetRandomLocations();[/B]
            //Get some random locations where the enemy will fire
            enemy.shootLocations = GetRandomShootingLocations(enemy.locationCords.Length - 1);
            //instansiate the enemy at the spawn position.
            Instantiate(enemy, spawnPosition, Quaternion.identity);
        }
        //increase the amount of enemies in the next wave.
        amountNewEnemysPerWave += 2;
        //Display the wave text.
        DisplayWave();
    }

    /// <summary>
    /// Returns a array of 2 random numbers.
    /// </summary>
    /// <param name="maxValue"></param>
    /// <returns></returns>
    private int[] GetRandomShootingLocations(int maxValue)
    {
        int[] returnValues = new int[2];
        returnValues[0] = UnityEngine.Random.Range(0, maxValue);
        returnValues[1] = UnityEngine.Random.Range(0, maxValue);

        return returnValues;
    }

    //Returns an array of 10 random locations.
    private Transform[] GetRandomLocations()
    {
        Transform[] returnValues = new Transform[10];
        for (int i = 0; i < 10; i++)
        {
            returnValues[I] = locationChords[UnityEngine.Random.Range(0, locationChords.Length - 1)];
        }
        return returnValues;
    }

    //Displays the wave text.
    void DisplayWave()
    {
        textTimer = Time.realtimeSinceStartup + 5;
        wavesText.text = "Wave: " + currentWave.ToString();

    }
}
[code/]


Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

I AM A SUPER NOOB!!! LOL I am just trying to figure things like this out, and I already fixed a few errors, but I am just taking stabs in the dark, I haven’t acquired the full skillsets to understand C# to fix this yet. I know that it is saying something is not right about these two lines of code, like it is saying maybe something is not assigned or doesn’t exist, but I don’t know how to fix it. This is like only my 3rd or 4th tutorial, and I really want to tackle this one, so I can move on to the next one, is could you please just help me figure this one out?

Hey use code tags…otherwise no one will bother to go through the code

This is great… Welcome!! Now that is a MASSIVE pile of code for a noob.

I recommend backing up and starting with very simple C# programming tutorial to understand what a reference is and exactly how a reference can be null. That’s not really an optional thing to learn. It’s mandatory.

Once you grasp that, looking through your code it will be FAR easier to grasp what can go wrong.

1 Like

Note that the actual error is the first line listed (61). Line 36 is calling Spawn(), which contains line 61. So there’s no error in line 36 per se, it’s calling a function that contains an error. Look up “stack trace” for more on this, it will be extremely helpful to decipher error messages.

Your problem is most likely here:
var enemy = Resources.Load(“Enemy”); // something about the syntax is wrong

It’s not loading the “enemy” asset properly into your enemy variable. So when you try to do something with it, you get the NullReferenceException. Try commenting out line 61, you’ll probably get the same error but for line 63, where you try to access enemy again. Make sense?

It can be tricky to track these things down, because an earlier error can cause later issues. The error says line 61, but in this case it’s most likely line 59, which doesn’t throw an error. Not all mistakes will.

I know, I know, but this tutorial was more for me to grasp the concepts of the game assets rather than the code, this is the final step in the game I was creating, I just want to finish this part and go onto c# Basics.

Can you help solv e this issue?

Thanks, I did it, now I know, and Knowing is half the Battle, GI JOE!!!

 using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waves : MonoBehaviour
{
    // Text to display what wave is next
    public TMPro.TextMeshPro wavesText;
    //The amount of enemies that each wave will increase by
    public int amountNewEnemysPerWave = 2;
    //The location coordinates for the enemies
    public Transform[] locationChords;
    //Locations where enemy will shoot.
    public int[] shootingLocations;
    //Counter keeping track of the amount of enemies previous wave.
    private int enemysLastWave = 1;
    //Spawn positions for the enemies.
    private Vector3 spawnPosition;
    //Current wave number
    private int currentWave = 0;
    //Timer to remove wave text
    private float textTimer = 0;

    private void Start()
    {
        Spawn();
    }
    void Update()
    {
        //Find one gameobject with the tag enemy in the scene
        var enemies = GameObject.FindGameObjectWithTag("Enemy");
        //If there are no enemies in the scene. Spawn new ones.
        if (enemies == null)
        {
            Spawn();[/B]
        }
        //remove the waves text when text timer is smaller than time since startup.
        if (textTimer < Time.realtimeSinceStartup)
        {
            wavesText.text = "";
        }
    }

    void Spawn()
    {
        //increase the current wave number
        currentWave++;
        //Set the correct number of enemies to the variable enemysLastWave. This is the same as writing enemysLastWave += amountNewEnemysPerWave;
        enemysLastWave = enemysLastWave + amountNewEnemysPerWave;
        //Loop to instansiate new enemies. run the loop for as many enemies there where last wave + as many new ones we add every wave.
        for (int i = enemysLastWave; i < enemysLastWave + amountNewEnemysPerWave; i++)
        {
            //Set a random spawn position of the enemy.
            spawnPosition.x = UnityEngine.Random.Range(-90, 90);
            spawnPosition.y = UnityEngine.Random.Range(-10, -70);
            spawnPosition.z = UnityEngine.Random.Range(80, 150);
            //Load a new Enemy from the enemy prefab in the Resource folder. It has to be in the folder called Resource.
            var enemy = Resources.Load<Enemy1>("Enemy");
            //Get a random set of locations that the enemy will travel between.
        enemy.locationCords = GetRandomLocations();[/B]
            //Get some random locations where the enemy will fire
            enemy.shootLocations = GetRandomShootingLocations(enemy.locationCords.Length - 1);
            //instansiate the enemy at the spawn position.
            Instantiate(enemy, spawnPosition, Quaternion.identity);
        }
        //increase the amount of enemies in the next wave.
        amountNewEnemysPerWave += 2;
        //Display the wave text.
        DisplayWave();
    }

    /// <summary>
    /// Returns a array of 2 random numbers.
    /// </summary>
    /// <param name="maxValue"></param>
    /// <returns></returns>
    private int[] GetRandomShootingLocations(int maxValue)
    {
        int[] returnValues = new int[2];
        returnValues[0] = UnityEngine.Random.Range(0, maxValue);
        returnValues[1] = UnityEngine.Random.Range(0, maxValue);

        return returnValues;
    }

    //Returns an array of 10 random locations.
    private Transform[] GetRandomLocations()
    {
        Transform[] returnValues = new Transform[10];
        for (int i = 0; i < 10; i++)
        {
            returnValues[I] = locationChords[UnityEngine.Random.Range(0, locationChords.Length - 1)];
        }
        return returnValues;
    }

    //Displays the wave text.
    void DisplayWave()
    {
        textTimer = Time.realtimeSinceStartup + 5;
        wavesText.text = "Wave: " + currentWave.ToString();

    }
}
[code/]
 using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waves : MonoBehaviour
{
    // Text to display what wave is next
    public TMPro.TextMeshPro wavesText;
    //The amount of enemies that each wave will increase by
    public int amountNewEnemysPerWave = 2;
    //The location coordinates for the enemies
    public Transform[] locationChords;
    //Locations where enemy will shoot.
    public int[] shootingLocations;
    //Counter keeping track of the amount of enemies previous wave.
    private int enemysLastWave = 1;
    //Spawn positions for the enemies.
    private Vector3 spawnPosition;
    //Current wave number
    private int currentWave = 0;
    //Timer to remove wave text
    private float textTimer = 0;

    private void Start()
    {
        Spawn();
    }
    void Update()
    {
        //Find one gameobject with the tag enemy in the scene
        var enemies = GameObject.FindGameObjectWithTag("Enemy");
        //If there are no enemies in the scene. Spawn new ones.
        if (enemies == null)
        {
            Spawn();[/B]
        }
        //remove the waves text when text timer is smaller than time since startup.
        if (textTimer < Time.realtimeSinceStartup)
        {
            wavesText.text = "";
        }
    }

    void Spawn()
    {
        //increase the current wave number
        currentWave++;
        //Set the correct number of enemies to the variable enemysLastWave. This is the same as writing enemysLastWave += amountNewEnemysPerWave;
        enemysLastWave = enemysLastWave + amountNewEnemysPerWave;
        //Loop to instansiate new enemies. run the loop for as many enemies there where last wave + as many new ones we add every wave.
        for (int i = enemysLastWave; i < enemysLastWave + amountNewEnemysPerWave; i++)
        {
            //Set a random spawn position of the enemy.
            spawnPosition.x = UnityEngine.Random.Range(-90, 90);
            spawnPosition.y = UnityEngine.Random.Range(-10, -70);
            spawnPosition.z = UnityEngine.Random.Range(80, 150);
            //Load a new Enemy from the enemy prefab in the Resource folder. It has to be in the folder called Resource.
            var enemy = Resources.Load<Enemy1>("Enemy");
            //Get a random set of locations that the enemy will travel between.
        enemy.locationCords = GetRandomLocations();[/B]
            //Get some random locations where the enemy will fire
            enemy.shootLocations = GetRandomShootingLocations(enemy.locationCords.Length - 1);
            //instansiate the enemy at the spawn position.
            Instantiate(enemy, spawnPosition, Quaternion.identity);
        }
        //increase the amount of enemies in the next wave.
        amountNewEnemysPerWave += 2;
        //Display the wave text.
        DisplayWave();
    }

    /// <summary>
    /// Returns a array of 2 random numbers.
    /// </summary>
    /// <param name="maxValue"></param>
    /// <returns></returns>
    private int[] GetRandomShootingLocations(int maxValue)
    {
        int[] returnValues = new int[2];
        returnValues[0] = UnityEngine.Random.Range(0, maxValue);
        returnValues[1] = UnityEngine.Random.Range(0, maxValue);

        return returnValues;
    }

    //Returns an array of 10 random locations.
    private Transform[] GetRandomLocations()
    {
        Transform[] returnValues = new Transform[10];
        for (int i = 0; i < 10; i++)
        {
            returnValues[I] = locationChords[UnityEngine.Random.Range(0, locationChords.Length - 1)];
        }
        return returnValues;
    }

    //Displays the wave text.
    void DisplayWave()
    {
        textTimer = Time.realtimeSinceStartup + 5;
        wavesText.text = "Wave: " + currentWave.ToString();

    }
}
[code/]

Do you know of any good resources for learning c# a little more?

When I first start it I learn the basic from a app call sololearn they have multiple languages you can learn after that I just Google more to learn more things that isn’t in there I’m still playing with it now too when I’m on my phone so i can play with the code example here https://code.sololearn.com/cpNMhg3lYbtH/?ref=app...maybe you could try it out