UI背包制作
1.制作预制体Cell(背包格子),Item(存放图片的预制体)
2.代码生成背包格子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIBag : MonoBehaviour
{
// Start is called before the first frame update
public GameObject Cell;//背包格子
public GameObject Item;//生成的物体
List<Transform> cells = new List<Transform>();//格子列表
void Start()
{
for (int i= 0;i<16;i++)//游戏开始生成背包格子16个
{
GameObject cell = Instantiate(Cell, transform);//函数作用:实现预制体。生成16个背包格子
cells.Add(cell.transform);//将格子位置添加到列表中
}
}
/// <summary>
/// 生成背包格子内物体
/// </summary>
/// <param name="Obj"></param>图片的名称
/// <param name="number"></param>Text内的数字,精灵数量
private void _Bag(string Obj, int number)
{
bool isbool = false;//执行下一行
for (int i = 0; i < 16; i++)
{
//当格子不为空时
if (cells[i].childCount > 0)
{
//位置 = transform.GetChild(1)//得到子物体的位置??0和1的意义
Transform weizhi = cells[i].GetChild(0);
//判断这个格子的子物体的名字与我们所生成的物体的名字相同
if (weizhi.GetComponent<Image>().sprite.name == Obj)//判断精灵的名字是否与格子内的精灵名字相同,如果相同
{
isbool = true;//布尔值变为true
Add_(weizhi.GetComponentInChildren<Text>(), number);//调用Add函数,物体的数量加1;
}
}
}
if (!isbool)//如果布尔值为false
{
//根据格子数量查询所有格子
for (int i = 0; i < cells.Count; i++)
{
//查询格子是否为空,当格子为空时
if (cells[i].childCount == 0)
{
//生成物体,添加图片
GameObject temp = Instantiate(Item);//实现放置精灵的预制体
temp.GetComponent<Image>().sprite = Resources.Load<Sprite>(Obj);//找到精灵图片
//将生成的物体作为当前个格子的子物体,位置归0
temp.transform.SetParent(cells[i]);//将temp的位置设置为父物体的位置
temp.transform.localPosition = Vector3.zero;//将temp的坐标设置为(0,0,0)
//已生成物体,终止当前for循环
break;
}
}
}
}
public void Add_(Text text,int number)//物体的数量
{
int temp = int.Parse(text.text);//将temp内Textstring类型转化为int类型
temp += number;//temp+number
text.text = "" + temp;//将Text格式转变为string类型
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.W))//如果按下W键
{
_Bag("Loading", 1);//调用_Bag函数,Loading为精灵体名字,数量为1
}
}
}