using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class cardcaozuo : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler { [Header("给一个canvas")] public Canvas canvas; [Header("显示的image")] public Image cardIconImage; [Header("对应的sprite")] public Sprite cardicon; [Header("目标点的名字")] public string targetTag; private Transform recordParent;//记录父节点 // Start is called before the first frame update void Start() { this.cardIconImage.sprite = cardicon; } // 拖拽开始 public void OnBeginDrag(PointerEventData eventData) { this.recordParent = this.transform.parent; this.transform.SetParent(canvas.transform); //throw new System.NotImplementedException(); } // 拖拽中 public void OnDrag(PointerEventData eventData) { this.transform.position = Input.mousePosition; } // 拖拽结束 public void OnEndDrag(PointerEventData eventData) { // 检测鼠标下的目标 List results = new List(); EventSystem.current.RaycastAll(eventData, results); foreach (var result in results) { if (result.gameObject.CompareTag(targetTag)) // 检测目标是否为目标点 { Debug.Log("成功放置到目标区域!"); transform.SetParent(result.gameObject.transform); // 设置为目标点的子物体 transform.localPosition = Vector3.zero; // 重置位置 this.enabled = false;//禁用自己 return; } } // 如果不在目标区域,返回原始父节点 Debug.Log("未放置到目标区域,返回原位置"); transform.SetParent(recordParent); transform.localPosition = Vector3.zero; // 重置到原始位置 } }