代碼:需要移動物體上的代碼(這裏是血瓶)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragDrop : MonoBehaviour,IPointerDownHandler,IBeginDragHandler ,IEndDragHandler,IDragHandler{
private RectTransform m_rectTransform;
public Canvas m_Canvas;
private CanvasGroup m_CanvasGroup;
void Start()
{
m_rectTransform = GetComponent<RectTransform>();
m_CanvasGroup = GetComponent<CanvasGroup>();
}
/// <summary>
/// 開始拖放前
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
m_CanvasGroup.blocksRaycasts = false;
m_CanvasGroup.alpha = 0.6f;
}
/// <summary>
/// 拖拽
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
m_rectTransform.anchoredPosition += eventData.delta/ m_Canvas.scaleFactor;
}
/// <summary>
/// 拖拽結束
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag拖拽結束");
m_CanvasGroup.blocksRaycasts = true;
m_CanvasGroup.alpha = 1f;
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("OnPointerDown");
}
}
代碼:物品格子代碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class IteamSlot : MonoBehaviour, IDropHandler
{
public void OnDrop(PointerEventData eventData)
{
if(eventData.pointerDrag!=null)
{
eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
}
}
}
把腳本放到格子上就行了,
有點不好,鼠標移動到格子上纔有放入的效果(有需要的可以試試)