背包系统优化
上一次发的背包其实不能算面向对象。只是一种面向过程的解决了背包的基本需求,这次更新面向对象该怎么实现背包。
多的就不说了,实现的效果是一样的,说一下脚本。
首先抽取一个抽象类BagItem,如下:
using UnityEngine;
//装备种类
public enum EquipType
{
//无类型
None,
//武器
Weapon,
//防具
Armor,
//鞋子
shoe
}
public abstract class BagItem : MonoBehaviour {
public EquipType type;
//背包格子接收方法
public abstract void Receive(Equipment equip);
}
然后,装备格子和背包格子用同一个脚本继承此抽象类,如下:
using UnityEngine;
public class BoxItem : BagItem
{ //用于判断是否为物品交换位置操作
public bool isExchange = false;
//重写方法
public override void Receive(Equipment equip)
{ //如果是空的普通格子
if (type == EquipType.None && (isExchange || transform.childCount == 0))
{ //放入格子
SingleTon.GetInstance().SetEquipToBox(equip.transform, transform);
}
//如果是空的装备格子且类型匹配
else if (type != EquipType.None && (isExchange || transform.childCount == 0) && equip.type == type)
{ //放入格子
SingleTon.GetInstance().SetEquipToBox(equip.transform, transform);
}
else
{ //回复原位
SingleTon.GetInstance().SetEquipToBox(equip.transform, equip.parent);
}
//标志位重置
isExchange = false;
}
}
然后写一个单例,用来执行移位操作
using UnityEngine;
public class SingleTon{
private static SingleTon instance;
private SingleTon() { }
public static SingleTon GetInstance()
{
if (instance == null)
{
instance = new SingleTon();
}
return instance;
}
//将装备放入指定格子
public void SetEquipToBox(Transform equip, Transform box)
{
equip.SetParent(box);
equip.localPosition = Vector3.zero;
equip.GetComponent<Equipment>().parent = box;
}
}
最后就是在装备上挂上脚本,同样继承抽象类
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Equipment : BagItem,IDragHandler,IBeginDragHandler,IEndDragHandler
{
//拿到图片组件
private Image image;
//记录父对象
public Transform parent;
void Awake()
{ //初始化图片组件
image = GetComponent<Image>();
}
void Start()
{ //记录父对象
parent = transform.parent;
}
public void OnBeginDrag(PointerEventData eventData)
{ //记录父对象
parent = transform.parent;
//可以理解为把所选装备放在屏幕的最前面以防被其他UI遮挡
transform.SetParent(transform.root);
//关闭图片射线检测
image.raycastTarget = false;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{ //拿到当前图片下的游戏对象的BagItem组件
BagItem bagItem = eventData.pointerEnter.GetComponent<BagItem>();
//如果不是空,调用接收方法
if (bagItem != null)
{
bagItem.Receive(this);
}
else
{ //否则复位
SingleTon.GetInstance().SetEquipToBox(transform, parent);
}
//开启图片射线检测
image.raycastTarget = true;
}
public override void Receive(Equipment equip)
{ //获取自己原来的格子
BoxItem myBox = parent.GetComponent<BoxItem>();
//获取目标的格子
BoxItem otherBox = equip.parent.GetComponent<BoxItem>();
//如果两个格子有一个是装备格子
if (myBox.type != EquipType.None || otherBox.type != EquipType.None)
{ //且二者类型不匹配
if (equip.type != type)
{ //回到格子的格子
myBox.Receive(this);
otherBox.Receive(equip);
return;
}
}
//程序走到这里,说明发生交换操作,将交换标志设为true
myBox.isExchange = true;
otherBox.isExchange = true;
//互相接收对方
myBox.Receive(equip);
otherBox.Receive(this);
}
}
点个关注,给个赞呗!