unity simple backpack system

Video reference: Unity tutorial: backpack system: 04: display in backpack (C# code) InventoryManager_ Beep beep beep_ bilibili

Material download:

https://pan.baidu.com/s/1o7_RW_QQ1rrAbDzT69ApRw

Extraction code: 8s95

1. Create a panel (modify it to the center mode: so that the length, width and height can be adjusted) and call it Bag 515 415

Just get a background box and a grid layout  
-----
2. Create database
    Use: scriptableobject API - > do not mount on the script

Create Item script (logic: store data)

        

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName ="New Item",menuName ="Inventory/New Item")]//Default name. What is the name of the right-click menu/
/// <summary>
///Attributes
/// </summary>
public class Items : ScriptableObject
{/// <summary>
///Name of the item
/// </summary>
    public string itemName;
    /// <summary>
    ///Pictures of items
    /// </summary>
    public Sprite itemImage;
    public int ItemHeld;///Quantity
        [TextArea]//Multi segment description and single line description do not need to be added
 /// <summary>
///Introduction
  /// </summary>
    public string ItemInfo;
/// <summary>
///Can I equip it
/// </summary>
    public bool equip;
}

----
Create Inventory script


  Create a script Inventory. I hope this backpack system is a list. It stores all my items in one backpack, so that different backpacks can be created: backpacks of blacksmith shop, backpacks of liquid medicine dealers, etc., and backpacks equipped with weapons

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory/New Inventory")]
public class Inventory : ScriptableObject
{
    public List<Items> itemList = new List<Items> ();
   // public Items[] itemlist;
}

In this way, the data in the item is stored in the Inventory backpack

list array and normal array:

list array common methods

1. Capacity gets the capacity size
2. Add element with add() method

3.3 insert () method inserts elements

4,[index] access element
5. Number of access elements of count attribute
6. The removeat () method removes the element at the specified location

7. The indexof () method obtains the index position in the list where an element is located
The method above LastIndexOf() is to search from the front to the back. This is to search from the back to the front. The search stops when the conditions are met. The above two methods return - 1 if the specified element is not found

8. Sort() sorts the elements in the list from small to large

9. Delete element.Remove

10. Judge whether an element is in the List

    List.Contains(T item) returns true or false

11. Reverse the order of the elements in the list. List.Reverse() can be used with List.Sort()

12. Clear list ()

13.List.FindAll method: retrieves all elements that match the conditions defined by the specified predicate  

14. The List.find method searches for elements that match the conditions defined by the specified predicate and returns the first matching element in the whole List

----

Create trigger condition: ItemOnWorld


  logic: when my game character encounters an item, I add 1 to the inventory
  Function realization:
  Drag items to the map and add necessary components (collider - > trigger). I want to write a code. This code is written on all items. As long as you touch the game character, it will be saved in the game character's bag
 
  logic: determine whether the game player collides with this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///logic: hang it on the script. I want to know which item we created belongs to this data,
///The generated variable tells uninty whether this is a sword or a shoe
/// </summary>
public class ItemOnWorld : MonoBehaviour
{[Tooltip("Items->Which database is the item")]
    public Items thisItem;
    [Tooltip("Which backpack does it belong to")]
    public Inventory PlayerInventory;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.CompareTag("Player"))
        {
            AddNewItem();//Add item
            Destroy(gameObject);
        }
    }

    public void AddNewItem()
    {
        if(!PlayerInventory.itemList.Contains(thisItem))
        {
            PlayerInventory.itemList.Add(thisItem);
            
        }
        else
        {
            thisItem.ItemHeld += 1;
        }
    }
}

add to:

stay ItemOnWord Inside AddNewItem Add statement segment



public void AddNewItem()
    {
        if(!PlayerInventory.itemList.Contains(thisItem))
        {
            PlayerInventory.itemList.Add(thisItem);
            InventoryManager.CreatNewItem(thisItem);
        }
        else
        {
            thisItem.ItemHeld += 1;
        }
    }

Replace (replace the method in itemworld)

 public void AddNewItem()
    {
        if(!PlayerInventory.itemList.Contains(thisItem))
        {
            PlayerInventory.itemList.Add(thisItem);
           // InventoryManager.CreatNewItem(thisItem);
        }
        else
        {
            thisItem.ItemHeld += 1;
            
        }
        InventoryManager.RefreshItem();
    }

------

Create backpack grid script: slot

Making backpack lattice instance prefab

logic: we're going to change the picture and number of prefab

Hanging scripts on prefab

public class Slot : MonoBehaviour
{
    public Items slotItem;
    public Image slotImage;
    public Text slotNum;
    
}

To realize the function, click the item to pop up the description and add it in the slot

public void ItemOnClicked()
    {
        isinfo = !isinfo;
        if (isinfo) { InventoryManager.UpdateItemInfo(slotItem.ItemInfo);}
        else { InventoryManager.UpdateItemInfo(""); }
        
    }

  Bind button click

Create an Inventorymanager mounted control script on the canvas

Hang the script manager on the canvas to control the instance

public class InventoryManager : MonoBehaviour
{
    static InventoryManager instance;

    //logic: which is the backpack? The items in the backpack should be generated
    public Inventory mabag;
    public GameObject slotgrid;//A prefab is generated within the scope of the grid
    public Slot slotPrefab;
    public Text itemInformation;

    private void Awake()
    {
        if (instance != null)
            Destroy(this);
        instance = this;
    }
    /// <summary>
    ///logic: hope to
    /// </summary>
    public static void CreatNewItem(Items item)
    {
        Slot newitem = Instantiate(instance.slotPrefab, instance.slotgrid.transform.position, Quaternion.identity);
        //Link locations
        newitem.gameObject.transform.SetParent(instance.slotgrid.transform);//Hang under the item to become a subset
        newitem.slotItem = item;
        newitem.slotImage.sprite = item.itemImage;
        newitem.slotNum.text = item.ItemHeld.ToString();
        //logic: the entity that generated the prefab is called newitem, but the newitem contains the function newitem, so the new item includes all the parameters in the slot

    }
}

At this time, we want to be able to open the backpack and see the items we want at the beginning, so the new writing method

InventoryManager


 private void Awake()
    {
        if (instance != null)
            Destroy(this);
        instance = this;
    }


public static void RefreshItem()
    {
        print("Refreshitem is running");
        print("instance.slotgrid.transform.childCount" + instance.slotgrid.transform.childCount);
        for (int i = 0; i < instance.slotgrid.transform.childCount; i++)//Loop to see how many subsets it has and destroy all subsets
        {
            print("instance.slotgrid.transform.childCount" + instance.slotgrid.transform.childCount);
            if (instance.slotgrid.transform.childCount == 0)
                break;
            Destroy(instance.slotgrid.transform.GetChild(i).gameObject);
        }

        for(int i=0; i <instance.mabag.itemList.Count;i++)
        {
            CreatNewItem(instance.mabag.itemList[i]);//Re created back
        }
    }

Replace the methods in itemworld

​​​​​​​

    public static void UpdateItemInfo(string itemDesciption)
    {
        instance.itemInformation.text = itemDesciption;
    }

----------------------

To realize the function, click the item to pop up the description, add it in the slot, and add it in the inventory manager

-----------

Achieve the drag effect: you can drag and drop it into other grids of the backpack, and change the position with other items in the backpack grid. Adjust the previous code

Previously, several grids were generated when several equipment were picked up

  This is equivalent to only two drawers

Let's create eighteen drawers first

Create a new button to store

  logic: you can change the item to another slot

If you want to drag it to other spaces in the backpack, we can uncheck the item button, so that we can judge that if the list does not contain this item, we will change its icon???

I hope these 18 grids can be saved in a list. Previously, we directly used one for convenience

Keywords: Unity

Added by morgan on Tue, 19 Oct 2021 10:44:19 +0300