NullReferenceException occuring, whilst nothing is wrong

This problem has been fixed*
I am working on making this system, that calculates a player’s stats, according to which items are equipped. This code works as it should and gets all the ‘calculations’ correct. I can also see that the code still gets run and is working, because when I, for example equip an item, then it changes the stats accordingly.

However, Unity, even though the list Inventory.Items is not null, and I am able to access it as I should, Unity keeps throwing the NullReferenceException to the line “if(inventory.items != null)”. And before I added this line, for demonstration it threw the error at the line “foreach (Item item in inventory.items)”.

using UnityEngine;
using System.Collections;

public class Player : Entity {

    // Player class variables
    public string playerClass;

    public CharacterInventory inventory;

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

    public void RecalculateStats ()
    {
        strength = 0;
        agility = 0;
        intellect = 0;
        spirit = 0;
        stamina = 2^level;
        if(inventory.items != null)
        {
            foreach (Item item in inventory.items)
            {
                strength += item.Strength;
                agility += item.Agility;
                intellect += item.Intellect;
                spirit += item.Spirit;
                stamina += item.Stamina;
            }
        }
        maxHealth = stamina * staminaMultiplier;
        if (currentHealth > maxHealth)
            currentHealth = maxHealth;
    }
}

The error sounds like not items but actually inventory is null. Have you debugged step by step and checked wether it is not?
From what you say (stats do get updated) it also sounds like that the issue changes during play. So sometimes works, sometimes not. Else you wouldnt get updated stats and null reference…

Yes, I have checked it step by step. But, the issue doesn’t change during play, the error comes every time this function is called, even though the function seems to work as it should. I’m not sure if it is a bug in Unity…

Sounds like inventory is null.

If you try to check Inventory.items when inventory itself is null, you’ll get the NullReferenceException.

I have checked this and neither Ínventory, nor Inventory.items are null. I have also tested this by being able to, for example run “Debug.Log(Inventory.items[0].ID);” and I would get the ID of that item and everything printed out in the console. But unity would still just then throw the NullReferenceException for this statement as well, even though it just ran it perfectly.

So you are saying that it is throwing the exception basically while it is successfully stepping through each line and doing the calculations? Because if it were the NullReferenceException it would basically stop executing the code at that exact line.

Yes, it runs the whole code as you explained. That is why I’ve gotten so confused as well and posted it here on the forums… I run Unity 5.5.2f1, by the way, if it could be a known bug.

I doubt it’s a bug in Unity. How are you setting up Inventory? I see it’s a public variable, is it a drag and drop in the inspector?

Do you have multiple Player scripts in your scene? Make sure by searching for Player scripts.

This is the function (in the CharacterInventory component) that I use to set up the items list:

public List<Item> items = new List<Item>();
void Start ()
    {
        slotPanel = inventoryPanel;

        slotAmount = 12;
        for (int i = 0; i < slotAmount; i++)
        {
            items.Add(new Item());
            slots.Add(slotPanel.transform.GetChild(i).gameObject);
            slots[i].GetComponent<CharacterSlot>().slotID = i;
            slots[i].GetComponent<CharacterSlot>().inv = this;
            slots[i].transform.SetParent(slotPanel.transform);
            slots[i].name = slots[i].GetComponent<CharacterSlot>().GetSlotName() + " (Empty)";
        }
    }

I reference to the CharacterInventory as a drag and drop, and I only have one object with the CharacterInventory component in the scene. I also only run one object in the scene with the Player component. The setup is shown here in these pictures:

Just a thing that might be important to say. This same code ran without errors in Unity 5.5.0f3 and I haven’t changed it since, I had made it work back then…

If you were getting the exception, the function wouldn’t work.

This means that what’s happening here is most likely that you have a second instance of the player script in your scene, and that’s the script that’s throwing the exception. So the instance of the script you’re looking at is working fine, but there’s some other object where the script has been added that doesn’t have any inventory linked.

Go in the hierarchy and search for “t:player”, that’ll show you all the gameobjects with the Player script attached to them.

1 Like

Thanks dude, sorry to everyone that I forgot to search for it, just in case, it turned out that I had a copy of the player low down in some hirearchy:roll_eyes: Whoops…

Yep, which is why I mentioned to search for Player. It’s not uncommon for this to happen on accident. I’ve seen it around the office sometimes either an accidental adding of the component or someone added a script, then got side tracked and added it again somewhere else. It happens.

Glad you got the issue fixed.

1 Like