0

I write Inventory script but this error was occured : NullReferenceException: Object reference not set to an instance of an object Inventory.set_SlotCnt (System.Int32 value) (at Assets/Scripts/Inventory/Inventory.cs:39) Inventory.Start () (at Assets/Scripts/Inventory/Inventory.cs:47)

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

public class Inventory : MonoBehaviour
{
    #region Singleton
    public static Inventory instance;
    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }
    #endregion

    public delegate void OnSlotCountChange(int val);
    public OnSlotCountChange onSlotCountChange;

    public delegate void OnChangeItem();
    public OnChangeItem onChangeItem;

    public List<Item> items = new List<Item>();


    private int slotCnt;

    Player player;

    public int SlotCnt
    {
        get => slotCnt;
        set
        {
            slotCnt = value;
            onSlotCountChange.Invoke(slotCnt);
        }
        
    }

    void Start()
    {
        player = Player.instance;
        SlotCnt = 0;
        
    }

    public bool AddItem(Item _item)
    {

        if (items.Count < SlotCnt) 
        {
            items.Add(_item);
            if (onChangeItem != null)
                onChangeItem.Invoke();
            return true;
        }
        return false;
    }

    public void RemoveItem(int _index)
    {
        SlotCnt--;
        items.RemoveAt(_index);
        onChangeItem.Invoke();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("FieldItem"))
        {
            SlotCnt++;
            FieldItems fieldItems = collision.GetComponent<FieldItems>();
            if (AddItem(fieldItems.GetItem()))
            {
                fieldItems.DestroyItem();
            }
        }
    }

    public void TryMountItem(int invenSlotIdx, Item item)
    {
        if (string.IsNullOrEmpty(item.itemName)) return;
        /*
        SlotCnt--;
        items.RemoveAt(invenSlotIdx);   
        onChangeItem.Invoke();*/

        player.ApplyItem(item, invenSlotIdx);
    }

}

I debug 'SlotCnt', but I couldn't find a case where a null value came to this variable

Support Ukraine
  • 39,592
  • 4
  • 35
  • 56

0 Answers0