背包系统已经完结。花了2天时间完成了这个背包系统,因为工作的原因拖了两天。上效果图:
上代码:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Item : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler,IBeginDragHandler,IDragHandler,IEndDragHandler,ICanvasRaycastFilter {
private static Transform canvas;
private Transform nowParent;
private bool isRaycast = true;
// Use this for initialization
void Start () {
if(canvas == null){
canvas = GameObject.Find ("Canvas").transform;
}
}
// Update is called once per frame
void Update () {
}
public void SetIcon(int id){
this.GetComponent<Image> ().sprite = KnapsackManager._instance.itemSprite [id];
}
public void OnPointerEnter(PointerEventData data){
KnapsackManager._instance.isShow = true;
}
public void OnPointerExit(PointerEventData data){
KnapsackManager._instance.isShow = false;
}
public void OnBeginDrag(PointerEventData data){
nowParent = transform.parent;
transform.parent = canvas;
isRaycast = false;
}
public void OnDrag(PointerEventData data){
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData data){
GameObject go = data.pointerCurrentRaycast.gameObject;
//当拖在有格子的地方时
if (go != null) {
Debug.Log (go.name);
//如果拖拽空格子里,就放在空格子里
if (go.tag.Equals("ItemParent")) {
SetPosition (transform, go.transform);
} else if (go.tag == "Item") {
SetPosition (transform, go.transform.parent);
SetPosition (go.transform, nowParent);
} else {
SetPosition (transform, nowParent);
}
} else {
SetPosition (transform, nowParent);
}
isRaycast = true;
}
void SetPosition(Transform item,Transform parent){
item.parent = parent;
item.position = parent.position;
}
public bool IsRaycastLocationValid(Vector2 sp,Camera eventCamera){
return isRaycast;
}
}
这个只是参考的背包系统,想要做好一点你可以自己扩展功能,或者代码质量好点。