1 设计背包背景,格子以及物品
背景
2 实现背包物品的创建
1 背景挂的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MyCells : MonoBehaviour {
public GameObject[] cells;//背包格子
public GameObject equip;//物品
public Sprite[] sprites;//物品样式
private int item;//随机数
private Sprite equidSprite;//随机生成的物品样式
void Start () {
}
void Update () {
if (Input.GetKeyDown(KeyCode.Q))
{
AddEquips();
}
}
void AddEquips()
{
item = Random.Range(0, sprites.Length);
equidSprite = sprites[item];
bool isOpen = false;//用来判断格子里是否有物品
for (int i = 0; i < cells.Length; i++)
{
if (cells[i].transform.childCount > 0)//格子里有子物体
{
MyEquid me = cells[i].GetComponentInChildren<MyEquid>();
if (me.image.sprite == equidSprite)
{
isOpen = true;
me.Addcount();//让物品的数量加1
break;
}
}
}
if (isOpen == false)
{
for (int i = 0; i < cells.Length; i++)
{
if (cells[i].transform.childCount == 0)
{
GameObject go = GameObject.Instantiate(equip) as GameObject;
go.transform.parent = cells[i].transform;//让创建出的物品成为格子的子物体
go.transform.localPosition = Vector3.zero;//让创建出来的物体局部坐标归零
Image im = go.GetComponent<Image>();
im.sprite = equidSprite;//让创建出来的物体图片变成随机出来的图片
break;
}
}
}
}
}
Paste_Image.png
2 物品挂的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MyEquid : MonoBehaviour {
public Text text;
public Image image;
private int count;
public void Addcount()
{
count++;
text.text = count + "";
}
}
Paste_Image.png
网友评论