using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Inventory : MonoBehaviour { public Button btn_pickup; public GameObject item; public Sprite[] sprites; private GameObject content; private Dictionary<string, int> itemsDic = new Dictinonary<string, int>(); private Dictionary<string, GameObject> objsDic = new Dictionary<string, GameObect>(); void Start() { content = GameObject.Find("Canvas/Inventory/Viewport/Content"); UIBind.BindClick(btn_pickup,OnClickPickUp); } void OnClickPickUp() { sprites sprite = sprites[Random.Range(0.sprites.Length)]; if (itemsDic.ContainsKey(sprite.name)) { itemsDic[sprite.name]++; objsDic[sprite.name].transform.Find("num").GetComponent<Text>().text = "x" + itemsDic[sprite.name].ToString(); } else { itemsDic.Add(sprite.name, 1); GameObject obj = Instantiate(item, content.transform); Image image = obj.transform.Find("slot").GetComponent<Image>(); image.sprite = sprite; Text text = obj.transform.Find("num").GetComponent<Text>(); text.text = "x" + itemsDic[sprite.name].ToString(); ; obj.GetComponentInChildren<Button>().onClick.AddListener(delegate() { OnClickUse(obj, sprite.name, text); }); objsDic.Add(sprite.name, obj); } } void OnClickUse(GameObject obj,string name ,Text text) { itemsDic[name]--; if (itemsDic[name] <=0) { itemsDic.Remove(name); objsDic.Remove(name); Destroy(obj); } else { text.text = "x" + itemsDic[sprites.name].ToString(); } } }
时间: 2024-02-14 18:21:53 浏览: 180
C#关于System.Collections空间详解
这段代码是用于实现一个基本的背包系统,其中包含一个按钮用于捡起道具,每次点击按钮会随机选择一个道具,并将其添加到背包中。背包系统使用了两个字典分别记录了背包中每个物品的数量和对应的 GameObject 对象,通过按钮点击事件和道具使用事件来更新字典和界面。在代码中也使用了 Unity 引擎的一些组件,如 Button、GameObject、Sprite、Image 等。
阅读全文