Inventory items and Documents, while both defined in the Inventory Manager, are treated as separate entities.
This script allows you to link the two together - so that adding a given Item to the Player's Inventory also gives you a specific Document, and interacting with that Item optionally opens the Document.
To use it:
- Create a Document, and an Inventory item to associate with it, in the Inventory Manager.
- In the Inventory Manager's Properties tab, define an Integer property named "Document ID"
- In the Inventory item's properties panel set the value of its "Document ID" property to match the ID number of the Document to associate it with (set to -1 to have no association)
- Create a new C# file named ItemDocument, and attach it to an object in the scene.
- Enter the ID of the "Document ID" proerty created in step 2 into the Item Document component's Inspector.
- (Optional) To have the Document automatically open when interacting with the Item, check Open On Interact, and assign an empty ActionList asset in the Item's "Standard Use" Interaction field.
ItemDocument.cs:
using AC;
using UnityEngine;
public class ItemDocument : MonoBehaviour
{
public int documentIDProperty = 0;
public bool openOnInteract;
private void OnEnable ()
{
EventManager.OnInventoryAdd += OnInventoryUpdate;
EventManager.OnInventoryRemove += OnInventoryUpdate;
EventManager.OnInventoryInteract += OnInventoryInteract;
}
private void OnDisable ()
{
EventManager.OnInventoryAdd -= OnInventoryUpdate;
EventManager.OnInventoryRemove -= OnInventoryUpdate;
EventManager.OnInventoryInteract -= OnInventoryInteract;
}
private void OnInventoryUpdate (InvItem invItem, int amount)
{
int documentID = invItem.GetProperty (documentIDProperty).IntegerValue;
if (documentID >= 0)
{
bool isCarryingItem = KickStarter.runtimeInventory.GetCount (invItem.id) > 0;
bool isCarryingDocument = KickStarter.runtimeDocuments.DocumentIsInCollection (documentID);
if (isCarryingItem != isCarryingDocument)
{
Document document = KickStarter.inventoryManager.GetDocument (documentID);
if (isCarryingItem) KickStarter.runtimeDocuments.AddToCollection (document);
else KickStarter.runtimeDocuments.RemoveFromCollection (document);
}
}
}
private void OnInventoryInteract (InvItem invItem, int iconID)
{
if (openOnInteract)
{
int documentID = invItem.GetProperty (documentIDProperty).IntegerValue;
if (documentID >= 0)
{
KickStarter.runtimeDocuments.OpenDocument (documentID);
}
}
}
}