1、创建一个工程
2、创建Panel(会自动创建Canvas 和EventSystem),将Panel中的Image组件删除,重命名为MainPanel。
3、在MainPanel下面创建Panel,调整大小,添加Grid Layout Group组件---能够自动的排列子物体。将Child Alignment改成Middle Center;
3、在Panel下面创建Panel,重命名slot,添加Grid Layout Group组件,将Cell Size中的x,y都改成90,Child Alignment改成Middle Center;
4、在slot中创建一个image,重命名为drag,在source Image添加图像。添加组件Canvas Group;拖拽到project作为预制体,删除slot下面的drag;
5、多复制几个slot,调整他们之间的间距
6、将Panel复制,调整位置,调整大小,可以多增加几个slot。将预制体drag拖拽到所有的slot中当子物体,并且改变里面的图像
7、创建脚本DragHandle,拖拽到drag预制体上,现在实现的功能:能够拖拽图片,但是松开鼠标后会回到初始的位置
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; // 导入命名空间 // 继承几个接口,用于拖拽 public class DragHandle : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler { // 拖拽的物体 public static GameObject itemBeginDragged; // 初始位置 Vector3 startPos; // 开始拖拽 public void OnBeginDrag(PointerEventData eventData) { itemBeginDragged = gameObject; startPos = transform.position; } // 拖拽中 public void OnDrag(PointerEventData eventData) { // transform.position = Input.mousePosition; } // 结束拖拽 public void OnEndDrag(PointerEventData eventData) { itemBeginDragged = null; transform.position = startPos; } }
8、修改上面的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; // 导入命名空间 // 继承几个接口,用于拖拽 public class DragHandle : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler { // 拖拽的物体 public static GameObject itemBeginDragged; // 初始位置 Vector3 startPos; // 记录拖拽物体的父物体 Transform startParent; // 开始拖拽 public void OnBeginDrag(PointerEventData eventData) { itemBeginDragged = gameObject; startPos = transform.position; startParent = transform.parent; // 拖拽的时候不能阻挡射线,不然一会在卡槽中放置的时候,射线射不到卡槽上 GetComponent<CanvasGroup>().blocksRaycasts = false; } // 拖拽中 public void OnDrag(PointerEventData eventData) { // transform.position = Input.mousePosition; } // 结束拖拽 public void OnEndDrag(PointerEventData eventData) { itemBeginDragged = null; // 结束拖拽后,让它能接受射线 GetComponent<CanvasGroup>().blocksRaycasts = true; // 如果没有设置新的父物体,就回到原来的地方。 if (transform.parent == startParent) { transform.position = startPos; } } }
9、创建脚本SlotHandle,拖拽到所有的slot,现在实现的功能是-能够往卡槽上拖拽图片,每个卡槽上只能放一个,没有放到卡槽上,会回到原来的地方
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class SlotHandle : MonoBehaviour,IDropHandler { public GameObject item { get { // 如果有子物体在返回,没有就为空 if(transform.childCount > 0) { return transform.GetChild(0).gameObject; } return null; } } // public void OnDrop(PointerEventData eventData) { // 如果上面没有物体,就能放置 if (!item) { DragHandle.itemBeginDragged.transform.SetParent(transform); } } }