一导入图片资源
- 导入
Sprite图片资源 - 修改图片检查器属性
- 纹理类型:
Sprite (2D和UI) - Sprite 模式: 多个
- 每单位像素数:32
- 过滤模式: 点 (无过滤器)
- 压缩: 无
- 打开
Sprite Editor -> 切片 -> 自动 -> 应用
二 创建预制件
- 新建
UI -> 画布重命名为BagObject - 删除
EventSystem: ui 对象与输入设备的交互事件系统。暂时不需要 修改
BagObject属性Canvas -> 勾选完美像素Canvas Scaler -> UI缩放模式: 屏幕大小缩放
BagObject下 新建空对象命名为BagBackgroundBagBackground添加Horizontal Layout Group水平排列组件BagObject下 新建空对象命名为SlotSlot属性:
Rect Transform: 80x80Slot下 新建UI -> 图像命名为ItemImageSlot下 新建UI -> 图像命名为BackgroundBackground下 新建UI -> 图像命名为TrayTray下 新建UI -> 图像命名为QtyText设置各对象背景图片及位置锚点
- 禁用
ItemImage -> Image组件显示 Background: 背景图片Tray: 背景图片
- 禁用
- 创建
Slot预制件 - 创建
BagObject预制件: 删除其中的Slot
三 编写脚本
新建
Slot类using UnityEngine; using UnityEngine.UI; public class Slot : MonoBehaviour { public Text qtyText; // qxtText 对象的引用 }新建
Bag类using UnityEngine.UI; using UnityEngine; public class Bag : MonoBehaviour { public GameObject slotPrefab; // slot预制件 public const int numSlots = 5; // 格子数量 Image[] itemImages = new Image[numSlots]; // 格子背景图 PropScriptable[] props = new PropScriptable[numSlots]; GameObject[] slots = new GameObject[numSlots]; // 格子对象 void Start() { CreateSlots(); } /// 创建格子 public void CreateSlots() { // 如果格子预制件存在 if (slotPrefab != null) { // 遍历生成 for (int i = 0; i < numSlots; i++) { GameObject newSlot = Instantiate(slotPrefab); newSlot.name = "propslot_" + i; newSlot.transform.SetParent(gameObject.transform.GetChild(0).transform); slots[i] = newSlot; // 添加到 slots 对象列表 itemImages[i] = newSlot.transform.GetChild(1).GetComponent<Image>(); // 添加图标到图标列表 } } } /// 添加道具到背包 public bool AddProp(PropScriptable prop) { // 遍历道具数量 for (int i = 0; i < props.Length; i++) { if (props[i] != null && props[i].itemType == prop.itemType && prop.stackable == true) { // Adding t existing slot props[i].quantity = props[i].quantity + 1; Slot slotScript = slots[i].GetComponent<Slot>(); Text quantityText = slotScript.qtyText; quantityText.enabled = true; quantityText.text = props[i].quantity.ToString(); return true; } if (props[i] == null) { props[i] = Instantiate(prop); props[i].quantity = 1; itemImages[i].sprite = prop.sprite; itemImages[i].enabled = true; return true; } } return false; } }更新
Player类...


立意高远,以小见大,引发读者对社会/人性的深层共鸣。
幽默外壳包裹严肃内核,寓教于乐。
代码示例规范,注释详细,便于复现。