Scripting2020-07-28T07:52:02+00:00

Scripting

Before you can use Inventory System through scripting you need to add the namespace to the top of your script.

using DevionGames.InventorySystem;
Finding items in database2020-07-28T07:14:05+00:00

Reference item in Unity Inspector. With this code snippet you can select a database item in the Unity Inspector.

using DevionGames.InventorySystem;

public class CustomScript: MonoBehaviour
{
    [ItemPicker(true)]
    public Item item;
}

Find an item in database by index.

Item item = ItemSystem.Database.items[index];

Find an item in database by name property using Linq.

Item item = ItemSystem.Database.items.Find(x => x.Name == "Sword");
Changes made to database items are persistent and will not be resetted on restart of the game. Instantiate the item if you need an instance of it.
Serialize ItemContainer2020-08-16T20:53:45+00:00

This code shows how you can serialize and deserialize ItemCollection for Inventory, Bank, Chest, Items in scene…

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

namespace DevionGames.InventorySystem
{
    public class SerializeItemCollection:MonoBehaviour
    {
        ItemCollection itemCollection;
        string serializedData = string.Empty;

        private void Start()
        {
            //Find Inventory
            ItemContainer container = UIWidgets.WidgetUtility.Find<ItemContainer>("Inventory");
            //Get ItemCollection for inventory
            itemCollection = container.GetComponent<ItemCollection>();
            //Serialize items in collection to a string
            serializedData = JsonSerializer.Serialize(itemCollection);
            //Here you can save it to PlayerPrefs, File, ScriptableObject, MySql or whatever
            Debug.Log(serializedData);
          
        }

        private void OnGUI()
        {
            if (GUILayout.Button("Deserialize"))
            {
                //Deserialize data from string
                Dictionary<string, object> dic = MiniJSON.Deserialize(serializedData) as Dictionary<string, object>;
                //Set data to item collection
                itemCollection.SetObjectData(dic);
            }
        }
    }
}
Finding items in ItemContainer2020-07-28T07:23:53+00:00

Find items by id.

private void Start()
{
    //Find ItemContainer by name
    ItemContainer container = WidgetUtility.Find<ItemContainer>("Inventory");
    //Get all item with given id
    Item[] items = container.GetItems(item.Id);
}

Find item by type and name.

private void Start()
{
    //Find ItemContainer by name
    ItemContainer container = WidgetUtility.Find<ItemContainer>("Inventory");
    //Get EquipmentItem(Type) by name. 
    EquipmentItem item = container.GetItems<EquipmentItem>().Where(x => x.Name == "Sword").FirstOrDefault();
}
Adding an item to ItemContainer2020-07-28T07:25:58+00:00

The following code adds an item to an ItemContainer with name “Inventory”. This method doesn’t check multiple ItemContainers. It uses the ItemContainer with highest priority.

private void Start()
{
    //Find ItemContainer by name
    ItemContainer container = WidgetUtility.Find<ItemContainer>("Inventory");
    //Add item to container
    if (container.AddItem(item)){
        //Item was added to inventory container
    }else {
        //Failed to add item
    }
}

Using a static method to add an item to an ItemContainer will check if the item can be added. If it fails to add the item, it will move to the next ItemContainer with the same name but lower priority. So if your main “Inventory” is full it will try to add the item to the next “Inventory”.

private void Start()
{
    //Add item to container
    if (ItemContainer.AddItem("Inventory", item, allowStacking)){
        //Item was added to inventory container
    }else {
        //Failed to add item
    }
}
Removing an item from ItemContainer2020-07-28T07:30:26+00:00

The following code removes an item from ItemContainer with name “Inventory”.

private void Start()
{
    //Find ItemContainer by name
    ItemContainer container = WidgetUtility.Find<ItemContainer>("Inventory");
    //Remove item from container
    if (container.RemoveItem(item, amount)){
        //Item was removed from inventory container
    }else {
        //Failed to remove item
    }
}

A static method includes all containers with name “Inventory”. If your main “Inventory” container doesn’t have the amount it will continue to search in lower priority container for the remaining amount.

private void Start()
{
    //Remove item from container
    if (ItemContainer.RemoveItem("Inventory", item, amount)){
        //Item was removed from inventory container
    }else {
        //Failed to remove item
    }
}
ItemContainer callbacks2020-07-28T07:34:52+00:00

Register to a container callback.

private void Awake()
{
    //Get the ItemContainer component from GameObject
    ItemContainer container = GetComponent<ItemContainer>();
    //Register to OnAddItem callback   
    container.OnAddItem += (Item item,Slot slot) =>
    {
        //Execute custom code when a new item is added.
        Debug.Log("[" + Time.time + "]" + "OnAddItem: " + item.Name + " Amount: " + item.Stack + " Container: " + slot.Container.Name + " Slot: " + slot.Index);
    };
}

Availible ItemContainer callbacks:

OnAddItem(Item item, Slot slot); Called when an item is added to the container.
OnFailedToAddItem(Item item); Called when an item could not be added to the container.
OnRemoveItem(Item item, int amount, Slot slot); Called when an item was removed from the container.
OnFailedToRemoveItem(Item item, int amount); Called when an item could not be removed.
OnUseItem(Item item, Slot slot); Called when an item was used from this container.
OnDropItem(Item item, GameObject droppedInstance); Called when an item was dropped from this container to world.
Accessing item properties2020-07-28T07:37:02+00:00

This code snippet finds an item property by name.

private void Start()  
{
    //Find "Strength" property
    ObjectProperty strength = item.FindProperty("Strength");
    //strength.GetValue(); //Use value
    //strength.intValue; //Value as an int
}
Randomize item property2020-07-28T07:38:54+00:00

Randomize item property in a percentage range.

//Randomize "Strength" property in range -20% to 20% 
item.RandomizeProperty("Strength", 0.2f);

Use custom randomization.

//Find "Strength" property 
ObjectProperty strength = item.FindProperty("Strength"); 
//Generate a random value between -5 and 8 
int random = Random.Range(-5, 8); 
//Apply random value to property 
strength.intValue = strength.intValue + random;
Creating custom ItemAction2020-07-28T07:41:10+00:00

To create a custom ItemAction extend from ItemAction and override the OnUpdate method. If your action requires multiple frames or time to complete you can return ActionStatus.Running until it is finished. Then return ActionStatus.Success to continue executing next action in list. Returning ActionStatus.Failure will stop the behaviour including all following acrions.

namespace DevionGames.ItemSystem.ItemActions{
    [Icon("Item")]
    [ComponentMenu("CustomCategory/CustomItemAction")]
    [System.Serializable]
    public class CustomItemAction : ItemAction{

        public override ActionStatus OnUpdate() {
            //Action behavior
            return ActionStatus.Success;
        }

    }
}

Custom ItemActions will be added automatically to the editor.

Trigger Callbacks2020-07-28T07:45:00+00:00
public class TriggerCallbackReceiver : MonoBehaviour, ITriggerUsedHandler
{
    public void OnTriggerUsed(GameObject player)
    {
        //Debug.Log("Trigger used.");
    }
}

To receive callbacks from trigger you need to implement one of the following callbacks.

ITriggerUsedHandler // Use this callback to detect trigger used events
void OnTriggerUsed(GameObject player);
ITriggerUnUsedHandler // Use this callback to detect trigger un-used events
void OnTriggerUnUsed(GameObject player);
ITriggerCameInRange // Use this callback to detect when player comes in range
void OnCameInRange(GameObject player);
ITriggerWentOutOfRange // Use this callback to detect when player went out of range
void OnWentOutOfRange(GameObject player);
ITriggerPointerEnter // Use this callback to detect when the pointer enters the trigger(Mouse over trigger)
void OnPointerEnter(PointerEventData eventData);
ITriggerPointerExit // Use this callback to detect when the pointer exits the trigger(Mouse not longer over trigger)
void OnPointerExit(PointerEventData eventData);
ITriggerSelectSellItem // Use this callback to detect when an item is selected for sell
void OnSelectSellItem(Item item, GameObject player);
ITriggerSoldItem // Use this callback to detect when an item was sold
void OnSoldItem(Item item, GameObject player);
ITriggerFailedToSellItem // Use this callback to detect when an item couldn’t be sold
void OnFailedToSellItem(Item item, GameObject player, Trigger.FailureCause failureCause);
ITriggerSelectBuyItem // Use this callback to detect when an item is selected for purchase
void OnSelectBuyItem(Item item, GameObject player);
ITriggerBoughtItem // Use this callback to detect when an item was bought
void OnBoughtItem(Item item, GameObject player);
ITriggerFailedToBuyItem // Use this callback to detect when a purchase failed(Often because no currency or if the inventory is full)
void OnFailedToBuyItem(Item item, GameObject player, Trigger.FailureCause failureCause);
ITriggerCraftStart // Use this callback to detect when the user starts crafting
void OnCraftStart(Item item, GameObject player);
ITriggerFailedCraftStart // Use this callback to detect when craft start failed, for example the player has no ingredients or if he is already crafting
void OnFailedCraftStart(Item item, GameObject player, Trigger.FailureCause failureCause);
ITriggerCraftItem // Use this callback to detect when the user crafted an item
void OnCraftItem(Item item, GameObject player);
ITriggerFailedToCraftItem // Use this callback to detect when the user failed to craft item
void OnFailedToCraftItem(Item item, GameObject player, Trigger.FailureCause failureCause);
ITriggerCraftStop // Use this callback to detect when the user stops crafting
void OnCraftStop(Item item, GameObject player);
Extending Trigger2020-07-28T07:47:03+00:00

Example how to extend Trigger.

using UnityEngine;
using DevionGames.InventorySystem;
using System.Collections.Generic;

public class CustomTrigger : Trigger
{
    //Override Callbacks property to add custom callbacks that will be shown in the Unity Inspector.
    public override string[] Callbacks
    {
        get
        {
            List callbacks = new List(base.Callbacks);
            callbacks.Add("OnCustomCallback");
            return callbacks.ToArray();
        }
    }

    //Override Use method
    public override bool Use(GameObject player)
    {
        //Can the trigger be used?
        if (!CanUse(player))
        {
            return false;
        }
        Trigger.currentUsedTrigger = this;
        //Set the trigger in use
        this.InUse = true;

        //Add custom code here that should be executed when the trigger is used.

        //Execute custom callback
        TriggerEventData triggerEventData = new TriggerEventData();
        triggerEventData.trigger = this;
        triggerEventData.player = InventoryManager.current.PlayerGameObject;
        Execute("OnCustomCallback", triggerEventData);

        return true;
    }

    //Override if you want to add behavior to trigger when an item is used.
    public override bool OverrideItemUse(Slot slot, Item item)
    {
        if (slot.Container.CanSellItems)
        {
            SellItem(item, item.Stack, true);
        }
        else if (Trigger.currentUsedWindow == slot.Container)
        {

            BuyItem(item, 1);
        }
        return true;
    }
}

 

Creating custom TriggerAction2020-07-28T07:49:20+00:00

This TriggerAction sets players rotation to look at the trigger.

namespace DevionGames.InventorySystem
{
    [Icon(typeof(Transform))]
    [ComponentMenu("Transform/Look At")]
    public class LookAtTrigger : TriggerAction
    {
        [SerializeField]
        private float m_Speed = 15f;

        private Quaternion m_LastRotation;
        private Quaternion m_DesiredRotation;

        public override void OnStart()
        {
            this.m_LastRotation = InventoryManager.current.PlayerGameObject.transform.rotation;
            this.m_DesiredRotation = m_LastRotation;
        }

        public override ActionStatus OnUpdate()
        {
            Vector3 targetPosition = transform.position;
            Vector3 gameObjectPosition = InventoryManager.current.PlayerGameObject.transform.position;
            targetPosition.y = gameObjectPosition.y;

            Vector3 dir = targetPosition - gameObjectPosition;
            if (dir.sqrMagnitude &gt; 0f)
            {
                m_DesiredRotation = Quaternion.LookRotation(dir);
            }

            m_LastRotation = Quaternion.Slerp(m_LastRotation, m_DesiredRotation, this.m_Speed * Time.deltaTime);
            InventoryManager.current.PlayerGameObject.transform.rotation = m_LastRotation;
            return Quaternion.Angle(m_LastRotation, m_DesiredRotation) > 5? ActionStatus.Running: ActionStatus.Success;
        }
    }
}
Custom trigger actions will be added automatically to triggers behavior menu.