- Notifications
You must be signed in to change notification settings - Fork0
An easy to use Unity inventory framework built with scaling and extendability in mind
License
Unity-for-Unity-Manufacturing/unity-elastic-inventory
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
An extendable Unity3D inventory library that leaves the implementation up to you. From simple inventory management to complex systems seen in Dark Souls, Diablo, Skyrim, ect. Stop rewriting your inventory and start building your game.
Features
- Instantly usable. Run the setup wizard, add an InventoryHelper, and you're done
- Built-in save/load support for customizable item properties (damage, durability, ect)
- Visual editor for managing item definitions
- Real-time inventory debugging
- Extendable item definitions (create weapons, tools, recipes, ect)
- Support for unique and stackable items
- Battle tested with automated tests
- Built for Unity (no integration overhead)
Support
Join theDiscord Community if you have questions or need help.
Here is a practicalPlayerInventory built with Elastic Inventory. You can shop, equip weapons, and use items. All with just a few lines of code.
usingUnityEngine;usingCleverCrow.Fluid.ElasticInventory;publicclassPlayerInventory:MonoBehaviour{publicInventoryHelperinventory;publicItemEntryWeaponweapon;// Access your currency easily at any timepublicintGold=>inventory.Instance.Get("gold")?.Quantity??0;// Ability to implement simple or complex purchasing logicpublicvoidBuyItem(ItemDefinitiondefinition){if(Gold<definition.cost)return;// Perform inventory CRUD with IDs or definitionsinventory.Instance.Add(definition);inventory.Instance.Remove("gold",definition.cost);}publicvoidEquipWeapon(stringweaponEntryId){// Use a custom weapon entry here to add properties like damage, durability, etc.weapon=inventory.Instance.GetEntry(weaponEntryId)asItemEntryWeapon;}publicvoidUseItem(ItemDefinitiondefinition){inventory.Instance.Remove(definition);// Use() is a custom method we've added. Heal a player, trigger an ability, whatever you wantdefinition.Use();}}
The above example assumes that you've created custom definitions and logic for your inventory. As Elastic Inventory's implementation is completely up to you, it serves as a bare-bones framework. Let's set up the ability to create items and make your first inventory in theGetting Started Guide.
- Getting Started Guide
- Documentation
- Recipes
- Developers Guide
Elastic Inventory is used throughUnity's Package Manager. In order to use it you'll need to add the following lines to yourPackages/manifest.json file. After that you'll be able to visually control what specific version of Elastic Inventory you're using from the package manager window in Unity. This has to be done so your Unity editor can connect to NPM's package registry.
{"scopedRegistries": [ {"name":"NPM","url":"https://registry.npmjs.org","scopes": ["com.fluid" ] } ],"dependencies": {"com.fluid.elastic-inventory":"1.0.1" }}Next you'll be greeted with a configuration wizard. Run it and you'll be able to create items by selecting theElasticInventory/Resources/ItemDatabase asset and clicking the edit button.
Before you create an item, we recommend customizing the automatically generated item definition atElasticInventory/ItemDefinition to your needs. This will allow you to add your own custom fields to items. Add acost field to the auto generated definition.
publicclassItemDefinition:ItemDefinitionBase{publicintcost;}
Now all items will have a cost field you can use to buy and sell items.
Add a gold item to theItemDatabase by clicking "Add". This will be used to purchase items. Make sure you set the definitionid to"gold" in the inspector (defaults to a randomly generated unique ID). I added an extra image field, you wont need to do that.
Also add a few quick items to buy such as a Mine Key and Longsword with a specified cost. We'll use these to purchase items for a player inventory. Here is an example of what that might look like if you added a lot of items.
Now add anInventoryHelper to a GameObject in a scene. This will automatically handle generating and maintaining an inventory for you. Add the gold to the starting items. Make sure you have enough gold to buy the items you want.
Last but not least, we need a script that facilitates item purchases. Let's create a script that automatically buys an item onStart with the logic we just wrote.
usingUnityEngine;usingCleverCrow.Fluid.ElasticInventory;usingSystem.Collections.Generic;publicclassPlayerInventory:MonoBehaviour{publicInventoryHelperinventory;publicList<ItemDefinition>itemsToBuy;voidStart(){foreach(variteminitemsToBuy){inventory.Instance.Remove("gold",item.cost);inventory.Instance.Add(item);}}}
Add the script, then attach the InventoryHelper to it and run the game. Notice that the item list on the InventoryHelper automatically updates its contents when run. This live debugging tool allows you to see what's in your inventory at any time.
Some of your names might differ from the above image. But when you run your UI, it should resemble this image.
Congratulations! You now have a fully functioning inventory. Refer to the guides and docs below for advanced usage.
Before you delve deeper, we recommend reading the following core concepts. These are the architectural patterns/concepts that drive Elastic Inventory.
The item database is a collection of item definitions. It's a scriptable object that can be edited in the Unity inspector. It's used to create and edit item definitions. At runtime a copy is lazy loaded for use by your inventory scripts.
An item entry is a reference to a living item in your inventory. It contains a reference to the item definition, timestamps, quantities, and other runtime specific data. It also contains a unique ID that can be used to reference the item in the inventory. Any data edited here will be automatically saved and loaded by the item entry data resolver.
An item definition is a template for an item. They form the backbone of the item entries' implementation. It contains a unique ID, a name, and any custom properties you've added to the definition. Note that definitions are static - they should never be edited at runtime. If you need to edit an item at runtime, use an item entry. Definitions can be stackable (default behavior) or unique (only one per stack).
We strongly recommend running the example store in the Assets/Examples/Shop folder. It's a fully functional store with a player and shop inventory. It demonstrates saving, loading, buying items, custom properties, and more, all with an easy-to-use interface.
To run it download/clone this repo and run the corresponding scene.
The inventory instance is a non-implementation specific representation of an inventory. It's a simple class that contains a list of items and a few helper methods. It's also serializable so it can be saved and loaded.
There are multiple ways to add an item. By definition, definition ID, or entry. Note that allAdd methods return anIItemEntryReadOnly interface that can be used to reference the item in the inventory. See the corresponding interface for more information.
// Add by definition referencevarentry=inventory.Instance.Add(definition,2);Debug.Log(entry.Id);// Unique ID of the entry// Add by definition ID. Note you must have a definition with the ID "sword" in your databaseinventory.Instance.Add("sword",1);// Entry should be a reference to an existing entry. The reference will be added to the inventory.// Primarily used for moving items between inventories and unique items// Make sure the entry is removed from the original inventory before calling thisoldInventory.Instance.RemoveEntry(entry.Id);inventory.Instance.AddEntry(entry);
There are multiple ways to remove an item. By definition, definition ID, or entry.
Please note that unique items can only be removed by callingRemoveEntry(ID). This is because a unique ID is required to remove an item when there are potentially multiple entries.
// Remove by definition referenceinventory.Instance.Remove(definition,1);// Remove by definition ID. Note you must have a definition with the ID "gold" in your database.inventory.Instance.Remove("gold",202);// Remove by entry ID reference. Note that every entry has a unique IDinventory.Instance.RemoveEntry("my-entry-id");
There are multiple ways to get an item entry. By definition, definition ID, or entry. If an item doesn't exist you will receive anull value.
// Get by definition referenceinventory.Instance.Get(definition);// Get by definition ID. Note you must have a definition with the ID "gold" in your database.inventory.Instance.Get("gold");// Get by entry referenceinventory.Instance.GetEntry("my-entry-id");
You can retrieve all items in an inventory. You can also specify an optionaldefinitionType and/orcategory to filter the results.
// Get all itemsinventory.Instance.GetAll();// Get all items of a specific definition typevartype=typeof(GearDefinition);inventory.Instance.GetAll(definitionType:type);// Get all items of a specific categoryinventory.Instance.GetAll(category:"weapon");// Get all items of a specific definition type and categoryinventory.Instance.GetAll(definitionType:type,category:"weapon");
You can easily check if an item exists by using a definition, definition ID, or entry ID.
// Check by definition referenceinventory.Instance.Has(definition,1);// Check by definition ID. Note you must have a definition with the ID "gold" in your database.inventory.Instance.Has("gold",202);// Check by entry reference IDinventory.Instance.HasEntry("my-entry-id");
Several events will automatically fire whenever an inventory is edited. This is extremely useful for UI updates and quests that require you to gather items. You can subscribe to these events with the following snippets.
// Subscribe to item added eventinventory.Instance.ItemAdded.AddListener((item)=>{Debug.Log("Item added: "+item.Definition.DisplayName);});// Subscribe to item removed eventinventory.Instance.ItemRemoved.AddListener((item)=>{Debug.Log("Item removed: "+item.Definition.DisplayName);});// Subscribe to item quantity changed event// Note this will fire when an item is added or removedinventory.Instance.ItemChanged.AddListener((item)=>{Debug.Log("Item quantity changed: "+item.Definition.DisplayName);});
As with all event subscriptions, it is recommended to unsubscribe when the object is destroyed. The easiest way to do this is subscribe to the event with a method reference. Then you can unsubscribe with the same method reference when you're done.
inventory.Instance.ItemAdded.RemoveListener(methodReferenceHere);
You can sort a list from GetAll in place by calling Sort on it. Sorting options include primary sort, secondary sort, order, and secondary order.
varitems=inventory.Instance.GetAll();// Sort by category, then alphabeticalinventory.Instance.Sort(items:items,sort:ItemSort.Category,sortSecondary:ItemSort.Alphabetical,orderSecondary:SortOrder.Ascending,);
You can also sort by a custom category order. This is useful if you want to sort multiple forms of gear or items in a specific order.
varitems=inventory.Instance.GetAll();varcustomCategorySort=newList<CategorySort>{new("Weapons",0),new("Armor",1),new("Consumables",2),new("Story",3),};inventory.Instance.Sort(items:items,sort:ItemSort.Category,customCategory:customCategorySort,);
You can save and load an inventory instance with the following snippets. This should only be done if you wish to create your own implementation ofInventoryInstance without using theInventoryHelper. It's recommended you use theInventoryHelper class to save and load inventories for simplicity.
// Save an inventory instancevarsave=inventory.Instance.Save();// Load an inventory instancevarinventoryInstance=newInventoryInstance(ItemDatabase.Current);inventoryInstance.Load(save);
You can create your own inventory instances with a custom implementation separate from an Inventory Helper. This will give you full granular control. See theInventoryInstance class and test file for more information.
The InventoryHelper is a light wrapper that automatically manages a simple implementation of an inventory instance for you with a lazy loadeddatabase. It's designed to only include the minimal logic required to get an inventory up and running. If you need more control, re-implement this instead of overriding it.
When callingSave() the inventory helper will automatically write data to aGlobalDatabaseManager singleton for you. It uses the ID in the inspector to generate a unique key.
inventoryHelper.Save();
There is noLoad method as the inventory helper will automatically load the inventory from the database every time it's initialized.
The item database is a container for all item definitions. When initially called at runtime a copy is created and stored in memory. That said you should not try to edit your item definition database at runtime.
You can get an item definition by ID. If an item definition doesn't exist you will receive anull value.
varitemDefinition=ItemDatabase.Current.Get("gold");
To save the database you only need to callSave(). This will write the database to aGlobalDatabaseManager singleton. Doing this is strongly recommended as the database keeps track of the total inventory item count in your project. The item count is used for specific kinds of sorting. If you notice issues with create at and updated at timestamps when sorting, it's likely because you haven't saved your database.
ItemDatabase.Current.Save();
If_autoLoad is checked you won't need to manage loading your database. As it will automatically pull from theGlobalDatabaseManager singleton. If you want to manually load your database you can do so with the following snippet.
ItemDatabase.Current.Load();
If you want to manage the save and load of your database by hand, there is a manual save and load method you can use.
varsave=ItemDatabase.Current.SaveManual();ItemDatabase.Current.LoadManual(save);
You can access the item database from anywhere in your code with the following snippet. It'll create a runtime instance if one doesn't already exist.
varitemDatabase=ItemDatabase.Current;
If your item definitions get out of sync. You can repair them by clicking the "Sync" button on the database. This will clear all your definition references and rebuild them from the Unity's Asset Database. Useful if you're manually editing item definitions in the project window.
Duplicate item definition IDs can cause issues in your project. Therefore, it is strongly recommended to repair the IDs if you clone or copy an item definition.
Elastic Inventory comes with a button on the database object called "Repair IDs." It will automatically repair all duplicate IDs and print the details to the logs. We suggest reviewing the logs. As you may need to adjust what IDs have been repaired to ensure save and load data doesn't get corrupted for items already in production.
Keep in mind item definition IDs are used to save and load your inventory. If you change IDs that existing saves are using, you will need to write your own migration code. Elastic inventory does not come with a tool to fix this. It's recommended to NEVER change item definition IDs that users are saving and loading in production.
The following examples demonstrate solutions to common tasks or situations you may encounter.
To add unique serialized fields to your items, such as a weapon with damage and energy cost, you can create custom item definitions. Here's a code snippet to illustrate this:
usingCleverCrow.Fluid.ElasticInventory;usingUnityEngine;// This attribute is required to register the item definition with the database and to give it a dropdown name[ItemDefinitionDetails("Weapon")]publicclassItemDefinitionWeapon:ItemDefinitionBase{[SerializeField]privateint_damage;[SerializeField]privateint_energyCost;// Add this category to the database's category list for filterability in the database editorpublicoverridestringCategory=>"Weapon";publicoverrideboolUnique=>true;publicintDamage=>_damage;publicintEnergyCost=>_energyCost;}
To create a custom item entry, extend the ItemEntryBase class. This allows you to add custom fields to the item entry. For instance, to add a level and durability field, refer to the following snippet:
usingCleverCrow.Fluid.ElasticInventory;publicclassItemEntryWeapon:ItemEntryBase{publicintLevel{get;set;}=1;publicintDurability{get;set;}=1000;}
To save and load the new entry fields above, create an ItemEntryDataResolver, a class that handles serialization and deserialization. This class will manage saving and loading your custom entry fields:
usingCleverCrow.Fluid.ElasticInventory;[System.Serializable]publicclassItemEntryDataResolverWeapon:ItemEntryDataResolverBase<ItemEntryWeapon>{publicintlevel;publicintdurability;protectedoverridevoidOnSave(ItemEntryWeaponitemEntry){level=itemEntry.Level;durability=itemEntry.Durability;}protectedoverridevoidOnLoad(ItemEntryWeaponitemEntry){itemEntry.Level=level;itemEntry.Durability=durability;}// Data resolvers are reused by each definition. It's recommended to reset data here to avoid data leakage between saving and loading itemsprotectedoverridevoidOnReset(){level=0;durability=0;}}
Lastly, inform your custom ItemDefinition about the new entry and data resolver. This can be achieved by adding the following logic:
publicclassItemDefinitionWeapon:ItemDefinitionBase{publicoverrideIItemEntryDataResolverDataResolver=>newItemEntryDataResolverWeapon();publicoverrideIItemEntryCreateItemEntry(IItemDatabasedatabase,intquantity=1,stringid=null,int?createdAt=null,int?updatedAt=null){// We have to initialize a new implementation of the entry here// This is because the database doesn't know about our custom entry typevarentry=newItemEntryWeapon();entry.Setup(database,this,quantity,id,createdAt,updatedAt);returnentry;}}
By default, items are stackable (adding multiple entries will increase the quantity). However, if you want to create a unique item that generates new entry every time it's added, override theUnique property on the item definition. This can be useful for gear, abilities, tools, or other items that should not stack:
usingCleverCrow.Fluid.ElasticInventory;publicclassMyUniqueItem:ItemDefinitionBase{publicoverrideboolUnique=>true;}
Saving and loading is handled automatically by theGlobalDatabaseManager singleton (unless manually implemented, which is not recommended). Nonetheless, you still need to restore theGlobalDatabaseManager save data. Here's a class that quickly enables saving and loading. Note, there are various ways to achieve this, and you may need to adjust the following code to suit your project:
usingSystem.Collections.Generic;usingCleverCrow.Fluid.Databases;usingCleverCrow.Fluid.ElasticInventory;usingUnityEngine;/// <summary>/// Please note this script must execute before the inventory helper and item database scripts/// You'll need to manually set the index in the script execution order window/// https://docs.unity3d.com/Manual/class-MonoManager.html/// </summary>publicclassInventorySaveHelper:MonoBehaviour{conststringSAVE_KEY="GLOBAL_DATABASE_SAVE";// Attach all your game's inventories here[SerializeField]List<InventoryHelper>_inventories;voidAwake(){if(!PlayerPrefs.HasKey(SAVE_KEY))return;// Restore the inventory databasevarsave=PlayerPrefs.GetString(SAVE_KEY);GlobalDatabaseManager.Instance.Load(save);}// Call this method to save all inventory datapublicvoidSave(){_inventories.ForEach(i=>i.Save());ItemDatabase.Current.Save();varsave=GlobalDatabaseManager.Instance.Save();// We're using PlayerPrefs to quickly save the data, but you can use whatever you want herePlayerPrefs.SetString(SAVE_KEY,save);}}
Item transfer between inventories is a frequent task. For instance, you may want to move an item from a player's inventory to a chest. The following snippet demonstrates how to do this:
publicvoidTransferItem(IItemEntryReadOnlyitem,intquantity,IInventoryInstancefrom,IInventoryInstanceto){from.RemoveEntry(item.Id,quantity);to.AddEntry(item);}inventory.TransferItem(entry,1,playerInventory,chestInventory);
In this example we're using theRemoveEntry andAddEntry methods to move the item. This approach is recommended when dealing with entries, as it prevents the loss of custom entry data (like durability and level) on unique items.
Note that stackable items will not transfer custom entry data. This is by design, as theAdd methods only modify the existing quantity of a stack. If you want to transfer custom entry data on stacks, you must manually handle it.
Not transferring stackable item entry data is by design. For instance, consider a healing flask with a quantity of 10 and a custom entry level of 2 to increase the healing amount. In this case, the player is buying/selling charges, not flasks. The flask bottle serves as a container. Therefore, when the player purchases 5 charges from a store, the default custom entry level of 1 in the store should not be transferred.
How to run the development environment and access various development tools.
Archives of specific versions and release notes are available on thereleases page.
To access nightly builds of thedevelop branch that are package manager friendly, you'll need to manually edit yourPackages/manifest.json as so.
{"dependencies": {"com.fluid.elastic-inventory":"https://github.com/ashblue/unity-elastic-inventory.git#nightly" }}Note that to get a newer nightly build you must delete this line and any related lock data in the manifest, let Unity rebuild, then add it back. As Unity locks the commit hash for Git urls as packages.
If you wish to run the development environment you'll need to install theNode.js version in the.nvmrc file. The easiest way to do this is installNVM and runnvm use.
Once you've installed Node.js, run the following from the root once.
npm install
If you wish to create a build runnpm run build from the root and it will populate thedist folder.
All commits should be made usingCommitizen (which is automatically installed when runningnpm install). Commits are automatically compiled to version numbers on release so this is very important. PRs that don't have Commitizen based commits will be rejected.
To make a commit type the following into a terminal from the root.
npm run commit
Please see theCONTRIBUTIONS.md file for full details on how to contribute to this project.
This project was generated withOyster Package Generator.
About
An easy to use Unity inventory framework built with scaling and extendability in mind
Resources
License
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Languages
- C#49.6%
- ShaderLab41.5%
- HLSL8.6%
- Other0.3%





