Forum rules - please read before posting.

Implementing inventory limit and object swap

I want to implement an inventory where the player can only carry one object at a time until they find a bag to store multiple Objects in.

Whilst they can only carry one item at a time, I’d like to enforce that the player swaps out the object they are carrying when picking up another item.

I will create an inventory with one item minimum, and I’d like the carried item to be displayed bottom left. How hard would it be to swap out objects that are places in the world?

Comments

  • If an item is swapped out, I assume that means it then appears in the scene as a new object?

    For each item, you'd need to create an associated prefab that represents it when placed in the scene - i.e. an object with the same sprite, and a Hotspot that makes it interactive.

    If you then assign that prefab in the item's Linked prefab field, you'd then access that through script to spawn into the scene if the inventory is full.

    The tricky part is handling the placement of the new item. If you wanted it to be in the same spot as the item you're swapping it with, you'll need to avoid the Inventory: Add or remove Action in favour of a script that handles both the inventory management and the object placement.

    Something along these lines, attached to the item prefabs:

    using UnityEngine;
    using AC;
    
    public class SwappableItem : MonoBehaviour
    {
    
        public string itemName;
    
        public void AttemptTake ()
        {
            if (KickStarter.runtimeInventory.PlayerInvCollection.GetCount (false) == 0)
            {
                KickStarter.runtimeInventory.Add (itemName);
                Object.Destroy (this);
            }
            else
            {
                Vector3 thisObjectPosition = transform.position;
                InvInstance invInstanceToRemove = KickStarter.runtimeInventory.PlayerInvCollection.InvInstances[0];
                if (invInstanceToRemove.InvItem.linkedPrefab)
                {
                    GameObject spawnedItemObject = Object.Instantiate (invInstanceToRemove.InvItem.linkedPrefab);
                    spawnedItemObject.transform.position = thisObjectPosition;
                }
                KickStarter.runtimeInventory.Remove (invInstanceToRemove);
            }
        }
    
    }
    

    Taking an item would then be a case of calling this script's AttemptTake function.

    Try it with a couple of test items first. You'll need to also use the Remember Transform component to save their scene presence.

  • Awesome! I will give it a shot!

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.