Unity-在Screen Space - Overaly的UI元素跟随鼠标的解决方案

using UnityEngine;
using UnityEngine.EventSystems;


/// 
/// Canvas为Screen Space - Overlay模式下
/// 
public class FollowMouse : MonoBehaviour
{
    private Vector2 offset;
    private RectTransform selectedRectTransform;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // 获取当前鼠标下的UI元素
            var pointer = new PointerEventData(EventSystem.current);
            pointer.position = Input.mousePosition;

            var results = new System.Collections.Generic.List();
            EventSystem.current.RaycastAll(pointer, results);

            if (results.Count > 0)
            {
                // 记录当前鼠标下的UI元素
                selectedRectTransform = results[0].gameObject.GetComponent();

                // 计算当前鼠标下的UI元素与鼠标位置的偏移量
                offset = (Vector3)selectedRectTransform.position - Input.mousePosition;
            }
        }
        else if (Input.GetMouseButton(0) && selectedRectTransform != null)
        {
            // 计算当前鼠标下的UI元素的位置
            selectedRectTransform.position = (Vector3)Input.mousePosition + (Vector3)offset;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            // 清空当前鼠标下的UI元素
            selectedRectTransform = null;
        }
    }
}

你可能感兴趣的:(unity小技巧,unity,c#,游戏引擎)