Hello, I’m trying to build my own inventory system, and I need to know how can I create “Item type”… That I attach script on item prefab and selec item type (weapon, clothes, consumable, etc…) and when I select weapon, then I must set weapon damage, weapon type (sword, mace, etc…) weapon lenght… Help me please, how to do that. Should I use enum?
It’s a rather generic question, so there’s really no way to give a specific answer…
Use a dictionary type list for storing what objects are in the inventory. You should derive all items from a common item baseclass that implements whatever functions you need for items, like selecting them (equipping a weapon, drinking a potion etc.). The actual item classes can be more diverse and implement the functionality each item should hold, like a weapon’s damage or a potion’s effect.
It would look something like this:
class Inventory {
// store item type and how many there are
var inventory : Dictionary.<ItemBase,int> = new Dictionary.<Item_Base,int>();
// adding an item to the inventory
function addItem( item : ItemBase ) {
if ( inventory.ContainsKey( item ) )
inventory[item] += 1;
else
inventory.Add(item ,1);
}
// remove and select functions
// generic inventory functions: sort, filter, etc.
}
Base Class for all items that implements basic inventory access function interfaces.
class ItemBase {
var owner : CarrierEntity; // class for entities with an inventory - probably the player
function InventoryAdd {
CarrierEntity.GetComponent.<Inventory>.addItem(this);
// keyword 'this' will automatically transform to the class of the child classes when called by them
}
function inventoryUse {
// like above ...
}
// more functions common to all items
}
Class for a potion item:
class ItemHealthPotion extends ItemBase {
// inherits functions InventoryAdd, inventoryUse, ... from base class
// add code specific to potions here
var healing : int;
var delay: float;
// ...
}
This last one is the class you’d actually apply to a prefab.
€dit:
Thinking about it, it’d be a more generic/robust implementation to index the inventory by prefab instead of script class.