搭建背包,给Panel添加网格布局组件(如图2),创建格子,给它们添加相同标签
创建物品的预制体,在预制体上添加Canvas Group组件
拾取物品
public Transform[] gezi;//格子的数组
public GameObject[] wupin;//物品的数组
private bool isLike = true;//是否有相同
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.X))//键盘事件调用方法
{
PickUpGet();
}
}
void PickUpGet()
{
isLike = true;
int index = Random.Range(0, wupin.Length);//随机数组下标
GameObject go = Instantiate(wupin[index]);//随机克隆物品
for (int i = 0; i < gezi.Length; i++)
{
if (gezi[i].childCount > 0 && go.name.Equals(gezi[i].transform.GetChild(0).name))//对比条件,格子是否有子物体并且子物体是否和克隆出来的物品名称相同
{
isLike = false;//有相同物品
int x = int.Parse(gezi[i].transform.GetChild(0).GetChild(0).GetComponent<Text>().text);//获取物品数量
gezi[i].transform.GetChild(0).GetChild(0).GetComponent<Text>().text = (x + 1).ToString();//添加物品数量
break;
}
}
if (isLike)//没有相同物品
{
for (int i = 0; i < gezi.Length; i++)
{
if (gezi[i].childCount == 0)//没有子对象
{
go.transform.parent = gezi[i];//将格子设为物品的父对象
go.transform.localPosition = Vector3.zero;//物品居中
break;
}
}
}
}
背包物品交换
打开脚本,添加两个Using指令
public class Bag : MonoBehaviour,IInitializePotentialDragHandler,IEndDragHandler,IBeginDragHandler,IDragHandler,IPointerEnterHandler,IPointerExitHandler//四个鼠标拖拽事件接口:初始化、开始前、进行中、结束
{
private CanvasGroup cg;
private Text tap;//提示文本框
void Start()
{
cg=GetComponent<CanvasGroup>();
tap = transform.GetChild(1).GetComponent<Text>();
}
public void OnInitializePotentialDrag(PointerEventData eventData)
{
}
public void OnBeginDrag(PointerEventData eventData)
{
cg.blocksRaycasts = false;//检测是否拖拽
}
public void OnDrag(PointerEventData eventData)
{
}
public void OnEndDrag(PointerEventData eventData)
{
cg.blocksRaycasts = true;
//GameObject go = eventData.pointerEnter;
if (eventData.pointerEnter!=null&& eventData.pointerEnter.gameObject.CompareTag("Wuti"))//判断格子中是否为空并且射线碰撞到的物体标签
{
GameObject go = eventData.pointerEnter;//碰撞对象
GameObject goParent = go.transform.parent.gameObject;//将碰撞到的物体的父物体储存起来
go.transform.parent = transform.parent;
transform.parent = goParent.transform;//替换父级对象
go.transform.localPosition = Vector3.zero;//将各自的相对坐标设置为0
transform.localPosition = Vector3.zero;
}
if (eventData.pointerEnter != null && eventData.pointerEnter.gameObject.CompareTag("Gezi"))
{
transform.parent = eventData.pointerEnter.transform;//直接将拖拽的物品的父级重置为碰撞的格子
transform.localPosition = Vector3.zero;
}
else
{
transform.localPosition = Vector3.zero;
}
}
public void OnPointerEnter(PointerEventData eventData)
{
tap.gameObject.SetActive(true);//鼠标放上显示
}
public void OnPointerExit(PointerEventData eventData)
{
tap.gameObject.SetActive(false);//鼠标移走不显示
}