Unity Losing My References "NullReferenceException: Object reference not set to an instance..."

Good evening everyone, I’m a Unity beginner and I’m following a tutorial to learn how to create an RPG.

So far I have not had any problems, I have been able to execute the lessons successfully.

However, after completing step 9.2 without problems to, getting the same result as the teacher. I saved my project and rebooted Unity. When i open the project and play, a new error has been displayed on the console.

As I did the tutorial three times to make sure I had not made any mistakes, I was able to record a short video in which I complete the tutorial and restart Unity. WATCH

"
NullReferenceException: Object reference not set to an instance of an object
UIManager.SetUseable (ActionButton btn, IUseable useable) (at C:/Users/Mystic Rabbit/Desktop/GameMaker/RPG v9.1/RPG/Assets/Scripts/Managers/UIManager.cs:112)
UIManager.Start () (at C:/Users/Mystic Rabbit/Desktop/GameMaker/RPG v9.1/RPG/Assets/Scripts/Managers/UIManager.cs:54)
"
I’m leaving the youtube link with the exact step of the tutorial I’m having problem. This will make it easier to understand the situation. I am also leaving the script pointed out by the error, so that you can analyze.

Remember, I did every tutorial 9.2, until the last second, I got the same positive results as the teacher in the video, but after restarting the software, this error appeared on the console.

Since I got a positive result, I think it’s a problem with Unity. I also tried “Rebuild Solution” but I could not fix this error.

Please someone help me, as I said I’m a beginner, I’m taking my first steps and I can not do it alone :frowning:

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

public class UIManager : MonoBehaviour
{
    private static UIManager instance;

    public static UIManager MyInstance
    {
        get
        {
            if (instance== null)
            {
                instance = FindObjectOfType<UIManager>();
            }

            return instance;
        }
    }

    /// <summary>
    /// A reference to all the action buttos
    /// </summary>
    [SerializeField]
    private ActionButton[] actionButtons;

    [SerializeField]
    private GameObject targetFrame;

    private Stat healthStat;

    [SerializeField]
    private Image portraitFrame;

    [SerializeField]
    private CanvasGroup keybindMenu;

    private GameObject[] keybindButtons;

    private void Awake()
    {
        keybindButtons = GameObject.FindGameObjectsWithTag("Keybind");
    }

    // Use this for initialization
    void Start()
    {
      
        healthStat = targetFrame.GetComponentInChildren<Stat>();

        SetUseable(actionButtons[0], SpellBook.MyInstance.GetSpell("Fireball"));
        SetUseable(actionButtons[1], SpellBook.MyInstance.GetSpell("Frostbolt"));
        SetUseable(actionButtons[2], SpellBook.MyInstance.GetSpell("Thunderbolt"));
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            OpenCloseMenu();
        }

    }

    public void ShowTargetFrame(NPC target)
    {
        targetFrame.SetActive(true);

        healthStat.initialized(target.MyHealth.MyCurrentValue, target.MyHealth.MyMaxValue);

        portraitFrame.sprite = target.MyPortrait;

        target.healthChanged += new HealthChanged(UpdateTargetFrame);

        target.characterRemoved += new CharacterRemoved(HideTargetFrame);
    }

    public void HideTargetFrame()
    {
        targetFrame.SetActive(false);
    }

    public void UpdateTargetFrame(float health)
    {
        healthStat.MyCurrentValue = health;
    }

    public void OpenCloseMenu()
    {
        keybindMenu.alpha = keybindMenu.alpha > 0 ? 0 : 1;
        keybindMenu.blocksRaycasts = keybindMenu.blocksRaycasts == true ? false : true;
        Time.timeScale = Time.timeScale > 0 ? 0 : 1;
    }

    public void UpdateKeyText(string key, KeyCode code)
    {
        Text tmp = Array.Find(keybindButtons, x => x.name == key).GetComponentInChildren<Text>();
        tmp.text = code.ToString();
    }

    public void CLickActionButton(string buttonName)
    {
        Array.Find(actionButtons, x => x.gameObject.name == buttonName).MyButton.onClick.Invoke();
    }

    public void SetUseable(ActionButton btn, IUseable useable)
    {
        btn.MyButton.image.sprite = useable.MyIcon;
        btn.MyButton.image.color = Color.white;
        btn.MyUseable = useable;
    }
}

This is wrong script. The error happend in line 111, but there are only 90 lines.

1 Like

Excuse me!!! I updated the code, the error is actually on line 54 and 112 :wink:

Null means that a reference variable is not set to anything. The error actually happens in line 112. Either your button is null or your usable is null. Use Debug.Log to output the value of those two variables to find out which one it is (unless it’s both).

2 Likes

Can you explain me, why did this mistake happen? I already understood the error … But I did not understand why it happened.

As I said before, I did everything exactly the same as the tutorial, I got all the positive results … Just after restarting Unity, that error started to appear.

Apparently this error was caused by the Unity that is losing the reference alone.

Look at this video, it was me that recorded, you will see that I can use all the skills … But after restarting Unity, simply everything stops working.

https://www.youtube.com/watch?v=kTabDddtjww

It does not make sense, it was not my mistake in the script, or a configuration error … It was simply the Unity that lost the reference …

There are two possibilities that I can think of: either actionButtons[0] is not set to a good value, or SpellBook.MyInstance.GetSpell(“Fireball”)) couldn’t find a value. Is there any chance you spelled “Fireball” differently when you added it? “FireBall” for example? If you use Debug.Log then you can figure out which of these is null,

1 Like

No, everything is spelled correctly. I believe that if it was just a typo, it would have appeared as soon as I gave play in the game … It does not look like a normal reference loss …

Did you try the debug.log yet?

By the way, why did you write
instance = FindObjectOfType<UIManager>();
instead of just assigning it like
instance = this;?
I realize you can’t put that in a static function, but you could put it in the Awake method or something. It’s not actually a singleton, after all. :slight_smile: Edit: I guess you’d have instance a static member for that to work.

I assume you did something similar with the SpellBook since you are referencing some kind of instance member? Are you sure it found itself? Also what about the actionButtons: did you assign these in the inspector?

1 Like

Null reference errors are resolved using the same process every time without exception. There is nothing unique about any situation where there is a different way depending on context. No videos need to be watched, nothing really needs to be explained. So I’m surprised null reference threads aren’t all just automatically closed with a comment to go to some generic sticky thread on the topic.

Do exactly this:

  1. Find the line where the error occurs
  2. Figure out what on that line are reference type variables you are accessing
  3. Add debugging before that line to figure out which of those reference type variables is the one which is null
  4. Figure out why, then make it not null

That’s all there is to it. If an easily reproducible null reference error takes you more than 10 minutes to figure out what is null, you’re doing it wrong.

  1. Line 112
  2. A quick look I’m guessing btn, btn.MyButton, btn.MyButton.image, usable, usable.MyIcon
  3. Add debugging something like this:
    public void SetUseable(ActionButton btn, IUseable useable)
    {
        if (btn == null)
        {
            Debug.Log("btn is null");
        }
        if (btn.MyButton == null)
        {
            Debug.Log("btn.MyButton is null");
        }
        if (btn.MyButton.image == null)
        {
            Debug.Log("btn.MyButton.image is null");
        }
        if (usable == null)
        {
            Debug.Log("usable is null");
        }
        if (usable.MyIcon == null)
        {
            Debug.Log("usable.MyIcon is null");
        }
        btn.MyButton.image.sprite = useable.MyIcon;
        btn.MyButton.image.color = Color.white;
        btn.MyUseable = useable;
    }
  1. You should now know which is null, so start investigating why, instead of being stuck for days on guessing which one is null
1 Like

Howdy, so just off a quick glance I would say based off the amount of Public/Serialized fields that chances are while your code is fine you’re missing a reference of that instance/object in the inspector. Meaning while you may have the right code there, you forgot to link something (probably your action buttons or current spell) in the inspector field in one of your items/scripts.

I didn’t watch the persons whole video, but a quick peek through showed at the end a modified word removed a reference, SpellBook script>Current Spell. He also bound the keys at about 22:53 on the UI Manager Script for the action buttons.

I would look through each script and make sure everything that should not be empty isn’t. It’s usually small things like that which get people on tutorials.

1 Like

I did this tutorial three times to make sure it would be all correct. If you see the video I recorded, you will realize that I was able to do everything without problems … The error only happens after restarting Unity. Watch the video have 1 minute.

Thanks for the tip, kdgalla had already asked me to do Debug, but since I am a beginner I did not know exactly how to do it, I was reading other articles to learn, but you helped me!

Now I will try to solve it, if you have some more tips, I will be grateful!

Anyway, I still have a big question that was not answered, if you watch the 1 minute video I recorded showing the final test process, you will realize that I was able to do the 100% tutorial. The error only happens after restarting Unity. That is, I make the spells work, but after restarting, the error happens.

I want to know how to restart Unity can cause this error?

Anyone here at the Unity forum would know how to solve this problem? I took this error to my programming teacher, he analyzed my scripts, analyzed my Unity settings, he saw the video I recorded for 1 minute demonstrating the moment that the error started to appear … But even after debbug, he also could not understand where the error is coming … As I said before, I followed step by step the whole tutorial, I was able to do everything, I repeat: I CAN DO ALL … but the unity itself, after restarting it has lost the references …

I re-read the whole tutorial, in front of my teacher, to be more than sure it was not a simple mistake of mine …

Does anyone have any idea how to solve this problem? I’ve done the debug, I have rewritten the scripts … But it does not work … Unity can not find the references.

Ok, now that you did the Debug.Log and shared the results, we know that it is btn.MyButton that is null. Now does this happen when you call this method for actionButtons[0], actionButtons[1], or actionButtons[2]? Each of these are ActionButton components attached to objects in your scene, right? Your ActionButton code has a field called MyButton and at least one of them is null. So the error is probably not a problem with UIManager.cs, but rather with one of these actionButtons entries. You see?

Is MyButton something that you assign in the inspector for those button objects, or do you assign it using some sort of code that is attached to those button objects?

THe basic strategy is, once you know what field is null, then you have to trace that field back to the beginning- Find out where it came from, whether it was ever assigned a value, or whether it was assigned a bad value along the way.

So did you solve this problem? I have exactly same problem!! Anyone know it??

The answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

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.

This is the kind of mindset and thinking process you need to bring to this problem:

https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

Step by step, break it down, find the problem.

Please start your own fresh thread in the future; don’t hijack old threads as it is against forum rules.