Home > Enterprise >  Unity Inventory System 'error CS1001: Identifier expected'
Unity Inventory System 'error CS1001: Identifier expected'

Time:12-23

I am writing a simple script to create an inventory system, although I keep getting an 'Identifier Expected' error. I am trying to select the current item the script is attached to and add it to the inventory.

This is the error:

Assets\Scripts\ItemObject.cs(10,25): error CS1001: Identifier expected

The tutorial I am following: https://www.youtube.com/watch?v=SGz3sbZkfkg


Here is the Inventory System:

InventorySystem.cs

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

public class InventorySystem : MonoBehaviour
{
    private Dictionary<InventoryItemData, InventoryItem> m_itemDictionary;
    public List<InventoryItem> inventory {get; private set;}

    private void Awake() {
        inventory = new List<InventoryItem>();
        m_itemDictionary = new Dictionary<InventoryItemData, InventoryItem>();
    }

    public void Add(InventoryItemData referenceData) {
        if(m_itemDictionary.TryGetValue(referenceData, out InventoryItem value)) {
            value.AddToStack();
        } else {
            InventoryItem newItem = new InventoryItem(referenceData);
            inventory.Add(newItem);
            m_itemDictionary.Add(referenceData, newItem);
        }
    }

    public void Remove(InventoryItemData referenceData) {
        if (m_itemDictionary.TryGetValue(referenceData, out InventoryItem value)) {
            value.RemoveFromStack();

            if(value.stackSize == 0) {
                inventory.Remove(value);
                m_itemDictionary.Remove(referenceData);
            }
        }
    }
}

 [Serializable]
public class InventoryItem {
    public InventoryItemData data {get; private set;}
    public int stackSize {get; private set;}

    public InventoryItem(InventoryItemData source) {
        data = source;
        AddToStack();
    }

    public void AddToStack() {
        stackSize  ;
    }

    public void RemoveFromStack() {
        stackSize--;
    }
}

and here is the script that handles the item pickup:

ItemObject.cs

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

public class ItemObject : MonoBehaviour {
    public InventoryItemData referenceItem;

    public void OnHandlePickupItem() {
        InventorySystem.this.Add(referenceItem);
        Destroy(gameObject);
    }
}

Any help would me much appreciated :)

CodePudding user response:

You can not refer to InventorySystem with InventorySystem.this.Add(referenceItem) in ItemObject.

Try following:

  • Add the InventorySystem component to a GameObject in your Scene
  • Tag this GameObject with a tag named Inventory
  • With that you can find the InventorySystem by GameObject.findByTag (do this in the Awake method of ItemObject
  • Use this object for adding/removing stuff from/to the InventorySystem
  • Related