Why is there a NullReferenceException when there is no object being referenced?

public GameObject LevelUpUI;
    delegate void methodGrabber();
    List<(string Name, methodGrabber Value)> methods1;
    int index1;
    public TMP_Text A1;

void Start()
    {
        methods1 = new List<(string Name, methodGrabber Value)>();
        methods1.Add((nameof(ProjectileSizeUp), ProjectileSizeUp));
        methods1.Add((nameof(ProjectileSpeedUp), ProjectileSpeedUp));
        methods1.Add((nameof(ProjectileNumberUp), ProjectileNumberUp));
    }

void OnEnable()
    {
        method1();
    }

void method1()
    {
        index1 = Random.Range(0, methods1.Count + 1);//this is where the error occurs
        A1.text = methods1[index1].Name;
    }

public void ButtonFunc0()
    {
        methods1[index1].Value();
        LevelUpUI.SetActive(false);
        Time.timeScale = 1;
    }

This is a condensed version of my code. It occurs nowhere else, even though I have multiple of these functions. Does anyone know why this could be?

It’s always helpful to include the error as it shows a line number. Granted, with a condensed version of your code, it wouldn’t really match up, so you’d want to include what line the error is pointing to.

But for references. Both your LevelUpUI and A1 variables are references. So it’s possible either could be null.

Try Methods.Count - 1 to stay within the index range.

1 Like

You are referencing MANY different things above that could be null.

Nope, but only YOU can find out. It’s ALWAYS the same three steps, ALWAYS.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

For one, the OnEnable is going to run LONG before Start() runs.

1 Like

I included it, here in the condensed code it is line 22, where I put a comment.

The thing is, it was working before, but I changed a few things so that the behavior would be as I wanted. And thanks for the information about OnEnable, I had just assumed that it would run after start does, that’s likely where the issue is popping up. I’ll get back to you after I’ve tried changing Start to Awake.

Well, it seems to have worked. Thanks for you’re help!

This is definitely a diagram that I cannot live without:

Here is some timing diagram help:

In addition, your use of Random will fail if you’re using UnityEngine.Random.Range() like that.

The Integer form of UnityEngine.Random.Range() is inclusive on the bottom exclusive on the top. It’s designed that way so you don’t have to add one to pick a random element. If you do add one, you’ll eventually pick an index outside the range of your array.

4 Likes

OnEnable is called before OnStart so your methods1 list hasn’t been created yet.

1 Like