Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to represent an Item in an inventory?

Discussion in 'Scripting' started by Ahmed-C, Jan 9, 2016.

  1. Ahmed-C

    Ahmed-C

    Joined:
    Dec 19, 2013
    Posts:
    10
    Let's say I have 3 items. These 3 items can be picked up by the player and each of these 3 items has a function. Let's call that function UseItem();. The objects get destroyed as the player goes over them. This indicates that the player has picked up the item and the item no longer exists in the scene, instead the Items are inside the Players inventory and are represented by Item class.

    Problem is that the items can't be used because they are represented by the item class with an ID and Name. The game prefab is destroyed once the player goes over it like mentioned earlier so how can I use the items functions and such inside the inventory which is represented by the Item class?

    I was thinking whether it would be effective to move all the picked up items into an empty Transform which will be inside the player called Inventory. Inside that is all the picked up items. so If the player wants to use a certain item, all that needs to be done is just to enable the item and the functions can be used?
     
  2. kietus

    kietus

    Joined:
    Jun 4, 2013
    Posts:
    54
    Hi Ahmed,

    You can try to make your item as a prefab (with your custom class as component). And you use Resources.Load to spawn your object. You can wrap that in a class, something like: Factory.ObjectSpawn("items/apple");
     
  3. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Your idea of making all the items children of a parent Inventory object makes sense to me. If it works for your game and is simple enough, then that's great!

    Usually, I usually keep data in Item classes that are NOT MonoBehaviours. My Inventory is usually NOT a MonoBehaviour.

    When I need to display the item in a UI or in the game world, I would make a GameObject to display that item's data, but the data itself is not tied to any particular game object.