Search Unity

Question I don't want stacking in my inventory slots

Discussion in '2D' started by Shrubland, Nov 28, 2022.

  1. Shrubland

    Shrubland

    Joined:
    Sep 1, 2022
    Posts:
    2
    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.

    Code (CSharp):
    1. public class BoxSlot : MonoBehaviour
    2. {
    3.     public List<GoodCheese> goodCheeses;
    4.     public List<BadCheese> badCheeses;
    5.     public GameObject goodCheese;
    6.     public GameObject badCheese;
    7.     public GameObject boxSlot;
    8.    
    9.     private void OnTriggerEnter2D(Collider2D other)
    10.     {    
    11.             if (other.gameObject.tag == "GoodCheese")
    12.             {
    13.                 Debug.Log("Box Slot: Good Cheese!");
    14.                 other.transform.position = this.transform.position;
    15.             }
    16.  
    17.             if (other.gameObject.tag == "BadCheese")
    18.             {
    19.                 Debug.Log("Box Slot: Bad Cheese!");
    20.                 other.transform.position = this.transform.position;
    21.             }                    
    22.     }
    23.     private void OnTriggerExit2D(Collider2D other)
    24.     {
    25.         if (other.gameObject.tag == "GoodCheese")
    26.         {
    27.             Debug.Log("Box Slot: Good Cheese Exited Trigger!");
    28.            
    29.             transform.gameObject.tag = "slot";
    30.         }
    31.        
    32.         if(other.gameObject.tag == "BadCheese")
    33.         {
    34.             Debug.Log("Box Slot: Bad Cheese Exited Trigger!");            
    35.         }
    36.     }
    37. }

    Code (CSharp):
    1. public class GoodCheese : MonoBehaviour
    2. {
    3.     public const string LAYER_NAME = "Default";
    4.     public const string LAYER_NAME2 = "PickUpInspect";
    5.  
    6.     public int sortingOrder = 0;
    7.     private SpriteRenderer sprite;
    8.     public Rigidbody2D rb;
    9.     private Transform thisTF;
    10.     private bool isDragged = false;
    11.     private Vector3 mouseDragStartPosition;
    12.     private Vector3 spriteDragStartPosition;
    13.  
    14.     void Start()
    15.     {
    16.         sprite = GetComponent<SpriteRenderer>();
    17.         rb = GetComponent<Rigidbody2D>();
    18.         thisTF = GetComponent<Transform>();
    19.     }
    20.     public void OnTriggerEnter2D(Collider2D other)
    21.     {
    22.         if (other.tag == "slot")
    23.         {
    24.             Debug.Log ("Good Cheese: I entered slot!");
    25.             gameObject.GetComponent<Rigidbody2D>().constraints =
    26.                 RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY |
    27.                 RigidbodyConstraints2D.FreezeRotation;
    28.         }
    29.      
    30.         if (other.tag == "Zoom")
    31.         {
    32.             Debug.Log("Zooming in!");
    33.             Vector2 scaleUp = new Vector2(thisTF.localScale.x + 0.5f, thisTF.localScale.y + 0.5f);
    34.             thisTF.localScale = scaleUp;
    35.         }
    36.     }
    37.     public void OnTriggerExit2D(Collider2D other)
    38.     {
    39.         if (other.tag == "slot")
    40.         {                    
    41.                 rb.constraints = RigidbodyConstraints2D.None;
    42.                 rb.constraints = RigidbodyConstraints2D.FreezeRotation;        
    43.         }
    44.      
    45.         if (other.tag == "Zoom")
    46.         {
    47.             Vector2 scaleUp = new Vector2(thisTF.localScale.x - 0.5f, thisTF.localScale.y - 0.5f);
    48.             thisTF.localScale = scaleUp;
    49.         }
    50.     }
    51.  
    52.     private void OnMouseDown()
    53.     {
    54.         this.gameObject.layer = LayerMask.NameToLayer("PickUpInspect");
    55.         sprite.sortingLayerName = LAYER_NAME2;
    56.         sprite.sortingOrder = 5;
    57.  
    58.         isDragged = true;
    59.         mouseDragStartPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    60.         spriteDragStartPosition = transform.localPosition;      
    61.     }
    62.  
    63.     private void OnMouseDrag()
    64.     {
    65.         if (isDragged)
    66.         {
    67.             transform.localPosition = spriteDragStartPosition +
    68.                 (Camera.main.ScreenToWorldPoint(Input.mousePosition) - mouseDragStartPosition);
    69.         }
    70.     }
    71.     private void OnMouseUp()
    72.     {
    73.         this.gameObject.layer = LayerMask.NameToLayer("Default");
    74.             sprite.sortingLayerName = LAYER_NAME;
    75.             sprite.sortingOrder = 2;
    76.             isDragged = false;  
    77.     }
    78. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    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:

    https://forum.unity.com/threads/weapon-inventory-and-how-to-script-weapons.1046236/#post-6769558

    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: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    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:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    When in doubt, print it out!(tm)

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

    Shrubland

    Joined:
    Sep 1, 2022
    Posts:
    2
    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?
     
  4. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    210
    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 :p Just wanted to give my thoughts :D
     
    Last edited: Nov 28, 2022
    Shrubland and Kurt-Dekker like this.