NullReferenceException: Object reference not set to an instance of an object[Master inventory Asset]

Hello everybody ! (Sorry for my bad english, i’am french :))

I have some trouble with my unity’s script :confused: I want to use the " Master Inventory Asset" In my project.
Before, i want to said that i know what this error mean! I have to assign in the inspector the object what i want to get in my script.


I know that the other gameobject are not assigned, it’s alright for now^^

(The player prefab is not in the hierarchy at the start , he is instanciate after the start)

error:

But the problem here, i did it and nothing change …

It’s a inventory panel that i want to assign to my player , but my player he’s a Prefabs wich is instanciate after the start .
I try do do a private GameObject variable, and Get this object In the start with : " GameObject.Find(“PanelInventory”);

But the error stay the same …

The panel Inventory is in a canvas object, and itself in a"inventory" object"
I want to acces to it in the “Inventory script” , attached to my player Prefab , instanciate in the game a few second after the start…

Someone have some fix ? I don’t undertstant why it’s happening … :confused:

Thx for reading !
Quentin.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class PlayerInventory : MonoBehaviour
{
    public GameObject inventory;
    public GameObject characterSystem;
    public GameObject craftSystem;
    private Inventory craftSystemInventory;
    private CraftSystem cS;
    private Inventory mainInventory;
    private Inventory characterSystemInventory;
    private Tooltip toolTip;

    private InputManager inputManagerDatabase;

    public GameObject HPMANACanvas;

    Text hpText;
    Text manaText;
    Image hpImage;
    Image manaImage;

    float maxHealth = 100;
    float maxMana = 100;
    float maxDamage = 0;
    float maxArmor = 0;

    public float currentHealth = 60;
    float currentMana = 100;
    float currentDamage = 0;
    float currentArmor = 0;

    int normalSize = 3;

    public void OnEnable()
    {
        Inventory.ItemEquip += OnBackpack;
        Inventory.UnEquipItem += UnEquipBackpack;

        Inventory.ItemEquip += OnGearItem;
        Inventory.ItemConsumed += OnConsumeItem;
        Inventory.UnEquipItem += OnUnEquipItem;

        Inventory.ItemEquip += EquipWeapon;
        Inventory.UnEquipItem += UnEquipWeapon;
    }

    public void OnDisable()
    {
        Inventory.ItemEquip -= OnBackpack;
        Inventory.UnEquipItem -= UnEquipBackpack;

        Inventory.ItemEquip -= OnGearItem;
        Inventory.ItemConsumed -= OnConsumeItem;
        Inventory.UnEquipItem -= OnUnEquipItem;

        Inventory.UnEquipItem -= UnEquipWeapon;
        Inventory.ItemEquip -= EquipWeapon;
    }

    void EquipWeapon(Item item)
    {
        if (item.itemType == ItemType.Weapon)
        {
            //add the weapon if you unequip the weapon
        }
    }

    void UnEquipWeapon(Item item)
    {
        if (item.itemType == ItemType.Weapon)
        {
            //delete the weapon if you unequip the weapon
        }
    }

    void OnBackpack(Item item)
    {
        if (item.itemType == ItemType.Backpack)
        {
            for (int i = 0; i < item.itemAttributes.Count; i++)
            {
                if (mainInventory == null)
                    mainInventory = inventory.GetComponent<Inventory>();
                mainInventory.sortItems();
                if (item.itemAttributes[i].attributeName == "Slots")
                    changeInventorySize(item.itemAttributes[i].attributeValue);
            }
        }
    }

    void UnEquipBackpack(Item item)
    {
        if (item.itemType == ItemType.Backpack)
            changeInventorySize(normalSize);
    }

    void changeInventorySize(int size)
    {
        dropTheRestItems(size);

        if (mainInventory == null)
            mainInventory = inventory.GetComponent<Inventory>();
        if (size == 3)
        {
            mainInventory.width = 3;
            mainInventory.height = 1;
            mainInventory.updateSlotAmount();
            mainInventory.adjustInventorySize();
        }
        if (size == 6)
        {
            mainInventory.width = 3;
            mainInventory.height = 2;
            mainInventory.updateSlotAmount();
            mainInventory.adjustInventorySize();
        }
        else if (size == 12)
        {
            mainInventory.width = 4;
            mainInventory.height = 3;
            mainInventory.updateSlotAmount();
            mainInventory.adjustInventorySize();
        }
        else if (size == 16)
        {
            mainInventory.width = 4;
            mainInventory.height = 4;
            mainInventory.updateSlotAmount();
            mainInventory.adjustInventorySize();
        }
        else if (size == 24)
        {
            mainInventory.width = 6;
            mainInventory.height = 4;
            mainInventory.updateSlotAmount();
            mainInventory.adjustInventorySize();
        }
    }

    void dropTheRestItems(int size)
    {
        if (size < mainInventory.ItemsInInventory.Count)
        {
            for (int i = size; i < mainInventory.ItemsInInventory.Count; i++)
            {
                GameObject dropItem = (GameObject)Instantiate(mainInventory.ItemsInInventory[i].itemModel);
                dropItem.AddComponent<PickUpItem>();
                dropItem.GetComponent<PickUpItem>().item = mainInventory.ItemsInInventory[i];
                dropItem.transform.localPosition = GameObject.FindGameObjectWithTag("Player").transform.localPosition;
            }
        }
    }

    void Start()
    {
        //if (HPMANACanvas != null)
        //{
        //    hpText = HPMANACanvas.transform.GetChild(1).GetChild(0).GetComponent<Text>();

        //    manaText = HPMANACanvas.transform.GetChild(2).GetChild(0).GetComponent<Text>();

        //    hpImage = HPMANACanvas.transform.GetChild(1).GetComponent<Image>();
        //    manaImage = HPMANACanvas.transform.GetChild(1).GetComponent<Image>();

        //    UpdateHPBar();
        //    UpdateManaBar();
        //}

        if (inputManagerDatabase == null)
            inputManagerDatabase = (InputManager)Resources.Load("InputManager");

        if (craftSystem != null)
            cS = craftSystem.GetComponent<CraftSystem>();

        if (GameObject.FindGameObjectWithTag("Tooltip") != null)
            toolTip = GameObject.FindGameObjectWithTag("Tooltip").GetComponent<Tooltip>();
        if (inventory != null)
            mainInventory = inventory.GetComponent<Inventory>();
        if (characterSystem != null)
            characterSystemInventory = characterSystem.GetComponent<Inventory>();
        if (craftSystem != null)
            craftSystemInventory = craftSystem.GetComponent<Inventory>();
    }

    //void UpdateHPBar()
    //{
    //    hpText.text = (currentHealth + "/" + maxHealth);
    //    float fillAmount = currentHealth / maxHealth;
    //    hpImage.fillAmount = fillAmount;
    //}

    //void UpdateManaBar()
    //{
    //    manaText.text = (currentMana + "/" + maxMana);
    //    float fillAmount = currentMana / maxMana;
    //    manaImage.fillAmount = fillAmount;
    //}


    public void OnConsumeItem(Item item)
    {
        for (int i = 0; i < item.itemAttributes.Count; i++)
        {
            if (item.itemAttributes[i].attributeName == "Health")
            {
                if ((currentHealth + item.itemAttributes[i].attributeValue) > maxHealth)
                    currentHealth = maxHealth;
                else
                    currentHealth += item.itemAttributes[i].attributeValue;
            }
            if (item.itemAttributes[i].attributeName == "Mana")
            {
                if ((currentMana + item.itemAttributes[i].attributeValue) > maxMana)
                    currentMana = maxMana;
                else
                    currentMana += item.itemAttributes[i].attributeValue;
            }
            if (item.itemAttributes[i].attributeName == "Armor")
            {
                if ((currentArmor + item.itemAttributes[i].attributeValue) > maxArmor)
                    currentArmor = maxArmor;
                else
                    currentArmor += item.itemAttributes[i].attributeValue;
            }
            if (item.itemAttributes[i].attributeName == "Damage")
            {
                if ((currentDamage + item.itemAttributes[i].attributeValue) > maxDamage)
                    currentDamage = maxDamage;
                else
                    currentDamage += item.itemAttributes[i].attributeValue;
            }
        }
        //if (HPMANACanvas != null)
        //{
        //    UpdateManaBar();
        //    UpdateHPBar();
        //}
    }

    public void OnGearItem(Item item)
    {
        for (int i = 0; i < item.itemAttributes.Count; i++)
        {
            if (item.itemAttributes[i].attributeName == "Health")
                maxHealth += item.itemAttributes[i].attributeValue;
            if (item.itemAttributes[i].attributeName == "Mana")
                maxMana += item.itemAttributes[i].attributeValue;
            if (item.itemAttributes[i].attributeName == "Armor")
                maxArmor += item.itemAttributes[i].attributeValue;
            if (item.itemAttributes[i].attributeName == "Damage")
                maxDamage += item.itemAttributes[i].attributeValue;
        }
        //if (HPMANACanvas != null)
        //{
        //    UpdateManaBar();
        //    UpdateHPBar();
        //}
    }

    public void OnUnEquipItem(Item item)
    {
        for (int i = 0; i < item.itemAttributes.Count; i++)
        {
            if (item.itemAttributes[i].attributeName == "Health")
                maxHealth -= item.itemAttributes[i].attributeValue;
            if (item.itemAttributes[i].attributeName == "Mana")
                maxMana -= item.itemAttributes[i].attributeValue;
            if (item.itemAttributes[i].attributeName == "Armor")
                maxArmor -= item.itemAttributes[i].attributeValue;
            if (item.itemAttributes[i].attributeName == "Damage")
                maxDamage -= item.itemAttributes[i].attributeValue;
        }
        //if (HPMANACanvas != null)
        //{
        //    UpdateManaBar();
        //    UpdateHPBar();
        //}
    }



    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(inputManagerDatabase.CharacterSystemKeyCode))
        {
            if (!characterSystem.activeSelf)
            {
                characterSystemInventory.openInventory();
            }
            else
            {
                if (toolTip != null)
                    toolTip.deactivateTooltip();
                characterSystemInventory.closeInventory();
            }
        }

        if (Input.GetKeyDown(inputManagerDatabase.InventoryKeyCode))
        {
            if (!inventory.activeSelf)
            {
                mainInventory.openInventory();
            }
            else
            {
                if (toolTip != null)
                    toolTip.deactivateTooltip();
                mainInventory.closeInventory();
            }
        }

        if (Input.GetKeyDown(inputManagerDatabase.CraftSystemKeyCode))
        {
            if (!craftSystem.activeSelf)
                craftSystemInventory.openInventory();
            else
            {
                if (cS != null)
                    cS.backToInventory();
                if (toolTip != null)
                    toolTip.deactivateTooltip();
                craftSystemInventory.closeInventory();
            }
        }

    }

}

I had a little trouble understanding, but I think I get a basic idea. You have an inventory script in your scene and then you create a player and want the player to access the inventory script?

Why not just make your inventory script a singleton? Then just access it through it’s static reference to itself vs trying to create a reference in your players script?

Are you having trouble finding the prefab you want to instantiate? If so you need to do something like this:

// Drag your prefab from the hierarchy to here.
public GameObject  myPrefab;

// Later on in your code:
Instantiate(myPrefab);

Though it sounds like you have something different. Is PanelInventory in your scene all the time or do you instantiate it, and then try to assign it to the player?

Thx @Brathnann and @takatok !:slight_smile:

I think my explain are wrong … I post Screen in 10 Minutes And edit my post ^^’ Sorry about that !

My prefabs it’s instanciate like i want, it’s not the probleme :confused: But in my prafab , i have a Inventory script, In this inventory script, i have a public Game object to assign ( Panel inventory )
But when i assign this panel to my prefab and launch the game, i have this error :confused:

EDIT: I post my screen and the code in the first post , i hope that is more helpful! :slight_smile:

Ok. Let me try to make sure I understand. You have a player prefab that has player inventory script on it.
You have a PanelInventory in your scene.
You need to instantiate the player and add the PanelInventory to your player inventory script.

Just a note because Panelinventory is in your scene and player is being instantiated, you can’t assign the the panel before you instantiate.

I’m not a huge fan of GameObject.Find myself, but if you have to use it, use it in Awake I believe should work. If you can make the Inventory script a singleton, that might be a better way, but if not you could also have a manager script that is in your scene that has a public GameObject variable that you have your PanelInventory dragged into.

public class GameManager
{
    public static GameManager instance;
    public GameObject panelInventory; //Assign the PanelInventory object here with drag and drop

     void Awake()
    {
//Note you should also include a way to destroy gameobjects to avoid duplicate GameManagers.
         instance = this;
    }
}

//Within your player script

GameManager.instance.panelInventory; //Access the inventory panel through your gamemanager script

This is a quick and dirty type up. But maybe it will help you get an idea of how you could set things up.

I don’t undertsand something , In my player script, where i have to put the “GameManager.instance.panelInventory;”

i have to to a new Game object variable before ? and get the Gamanager object before ?

So, GameManager would be in your scene on an empty gameobject. You would drag your panelInventory into the slot in the inspector. Because the static reference to itself is created, you can access the GameManager script through that variable without having to create a reference to the GameManager in your player script.

Which is why you use GameManager.instance.panelInventory. This gives you access to the Panel Inventory gameobject that is in your scene.

//This line
mainInventory = inventory.GetComponent<Inventory>();

//would become this
mainInventory = GameManager.instance.panelInventory.GetComponent<Inventory>();

You can of course name the variables anything you want. I’m just trying to give you some guidance on how this works.

Okay ! i understand now :)! Thx a lot!!

And for the line “if (!inventory.activeSelf)” (ligne 306)

I have to change this too ?

EDIT: Nothing change :confused:

I call my class Scriptmanager

i replace all line MainInventory ect… by : mainInventory = Scriptmanager.instance.panelInventory.GetComponent();

and this :confused:

It’s make me crazy :hushed:

MIRACLE!! I did it T.T …

I just put on the void start : mainInventory = Scriptmanager.instance.panelInventory.GetComponent();

thank you so much !! my brain is going to explode !! :O!!

you save my night!! Thx again!!

Glad you were able to get it working!

1 Like

where did you put this? on GameMaster script or on panel inventory script? thx

i don’t understand can you specific the details about the GameManager? thx