【UI背包】----背包制作

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
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值