I don't want stacking in my inventory slots

Hey all, I am not quite making an inventory system, but it seems similar to one. I want to place an item into a slot and when that slot is full, then trying to put more items on top should collide with the physics of the filled slot and move out of the way rather than infinitely fill with more and more items stacking. I tried using booleans to make an isSlotFilled = true or false and check that but it wasn’t’ compatible with my code I have so far.

public class BoxSlot : MonoBehaviour
{
    public List<GoodCheese> goodCheeses;
    public List<BadCheese> badCheeses;
    public GameObject goodCheese;
    public GameObject badCheese;
    public GameObject boxSlot;
   
    private void OnTriggerEnter2D(Collider2D other)
    {     
            if (other.gameObject.tag == "GoodCheese")
            {
                Debug.Log("Box Slot: Good Cheese!");
                other.transform.position = this.transform.position;
            }

            if (other.gameObject.tag == "BadCheese")
            {
                Debug.Log("Box Slot: Bad Cheese!");
                other.transform.position = this.transform.position;
            }                     
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.tag == "GoodCheese")
        {
            Debug.Log("Box Slot: Good Cheese Exited Trigger!");
           
            transform.gameObject.tag = "slot";
        }
       
        if(other.gameObject.tag == "BadCheese")
        {
            Debug.Log("Box Slot: Bad Cheese Exited Trigger!");             
        }
    }
}
public class GoodCheese : MonoBehaviour
{
    public const string LAYER_NAME = "Default";
    public const string LAYER_NAME2 = "PickUpInspect";
 
    public int sortingOrder = 0;
    private SpriteRenderer sprite;
    public Rigidbody2D rb;
    private Transform thisTF; 
    private bool isDragged = false;
    private Vector3 mouseDragStartPosition;
    private Vector3 spriteDragStartPosition;

    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        rb = GetComponent<Rigidbody2D>();
        thisTF = GetComponent<Transform>();
    }
    public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "slot")
        {
            Debug.Log ("Good Cheese: I entered slot!");
            gameObject.GetComponent<Rigidbody2D>().constraints =
                RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY |
                RigidbodyConstraints2D.FreezeRotation;
        }
     
        if (other.tag == "Zoom")
        {
            Debug.Log("Zooming in!");
            Vector2 scaleUp = new Vector2(thisTF.localScale.x + 0.5f, thisTF.localScale.y + 0.5f);
            thisTF.localScale = scaleUp;
        }
    }
    public void OnTriggerExit2D(Collider2D other)
    {
        if (other.tag == "slot")
        {                    
                rb.constraints = RigidbodyConstraints2D.None;
                rb.constraints = RigidbodyConstraints2D.FreezeRotation;         
        }
      
        if (other.tag == "Zoom")
        {
            Vector2 scaleUp = new Vector2(thisTF.localScale.x - 0.5f, thisTF.localScale.y - 0.5f);
            thisTF.localScale = scaleUp;
        }
    }

    private void OnMouseDown()
    {
        this.gameObject.layer = LayerMask.NameToLayer("PickUpInspect");
        sprite.sortingLayerName = LAYER_NAME2;
        sprite.sortingOrder = 5;

        isDragged = true;
        mouseDragStartPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        spriteDragStartPosition = transform.localPosition;      
    }

    private void OnMouseDrag()
    {
        if (isDragged)
        {
            transform.localPosition = spriteDragStartPosition +
                (Camera.main.ScreenToWorldPoint(Input.mousePosition) - mouseDragStartPosition);
        }
    }
    private void OnMouseUp()
    {
        this.gameObject.layer = LayerMask.NameToLayer("Default");
            sprite.sortingLayerName = LAYER_NAME;
            sprite.sortingOrder = 2;
            isDragged = false;   
    }
}

These things (inventories, shop systems, character customization, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.

They contain elements of:

  • a database of items that you may possibly possess / equip
  • a database of the items that you actually possess / equip currently
  • perhaps another database of your “storage” area at home base?
  • persistence of this information to storage between game runs
  • presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
  • interaction with items in the inventory or on the character or in the home base storage area
  • interaction with the world to get items in and out
  • dependence on asset definition (images, etc.) for presentation

Just the design choices of an inventory system can have a lot of complicating confounding issues, such as:

  • can you have multiple items? Is there a limit?
  • if there is an item limit, what is it? Total count? Weight? Size? Something else?
  • are those items shown individually or do they stack?
  • are coins / gems stacked but other stuff isn’t stacked?
  • do items have detailed data shown (durability, rarity, damage, etc.)?
  • can users combine items to make new items? How? Limits? Results? Messages of success/failure?
  • can users substantially modify items with other things like spells, gems, sockets, etc.?
  • does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
  • etc.

Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

Breaking down a large problem such as inventory:

If you want to see most of the steps involved, make a “micro inventory” in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).

Everything you learn doing that “micro inventory” of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.

To understand what your code is doing, use this approach:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Hey Kurt, I will be saving this for all my future projects to look over. I appreciate your in depth response. I should reiterate what I mentioned at first, is that this isn’t exactly an inventory system. It’s really just placing things into slots, and then the slots should stop allowing things to be placed there. I’m trying to make it as simple as possible, partly because I am fairly new at this stuff. What would you recommend is the best thing to learn for that?

Best thing here I’d say is have an Inventory/SlotParent Class. Then your Slots are children of this Class. You pass the item you want into the SlotParent/Inventory Class, this loops all children Slots and checks to see if IsSlotFilled true for all Slots, if so, return early and don’t execute any more code.

Dunno if this counts as hijacking a thread, sorry if so Kurt :stuck_out_tongue: Just wanted to give my thoughts :smile:

2 Likes