83 lines
2.2 KiB
C#
83 lines
2.2 KiB
C#
using UnityEngine;
|
||
using UnityEngine.EventSystems;
|
||
|
||
public class CursorManager : MonoBehaviour
|
||
{
|
||
public static CursorManager Instance;
|
||
|
||
public Texture2D defaultCursor; // 默认光标
|
||
public Texture2D hoverCursor; // 悬停光标
|
||
|
||
private GameObject lastHoveredObject;
|
||
|
||
private void Awake()
|
||
{
|
||
if (Instance == null)
|
||
{
|
||
Instance = this;
|
||
DontDestroyOnLoad(gameObject);
|
||
}
|
||
else
|
||
{
|
||
Destroy(gameObject);
|
||
}
|
||
}
|
||
|
||
private void Update()
|
||
{
|
||
// 检测鼠标指向的物体
|
||
if (EventSystem.current.IsPointerOverGameObject())
|
||
{
|
||
PointerEventData pointerData = new PointerEventData(EventSystem.current)
|
||
{
|
||
position = Input.mousePosition
|
||
};
|
||
|
||
// 获取指针下的对象
|
||
var results = new System.Collections.Generic.List<RaycastResult>();
|
||
EventSystem.current.RaycastAll(pointerData, results);
|
||
|
||
if (results.Count > 0)
|
||
{
|
||
GameObject hoveredObject = results[0].gameObject;
|
||
|
||
// 判断是否为新的悬停物体,且是否实现了IPointer接口
|
||
if (hoveredObject != lastHoveredObject &&
|
||
(hoveredObject.GetComponent<IPointerEnterHandler>() != null ||
|
||
hoveredObject.GetComponent<IPointerClickHandler>() != null ||
|
||
hoveredObject.GetComponent<IPointerDownHandler>() != null))
|
||
{
|
||
Cursor.SetCursor(hoverCursor, Vector2.zero, CursorMode.Auto);
|
||
lastHoveredObject = hoveredObject;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
ResetCursor();
|
||
}
|
||
}
|
||
else
|
||
{
|
||
ResetCursor();
|
||
}
|
||
}
|
||
|
||
private void ResetCursor()
|
||
{
|
||
if (lastHoveredObject != null)
|
||
{
|
||
Cursor.SetCursor(defaultCursor, Vector2.zero, CursorMode.Auto);
|
||
lastHoveredObject = null;
|
||
}
|
||
}
|
||
|
||
public void SetHover()
|
||
{
|
||
Cursor.SetCursor(hoverCursor, Vector2.zero, CursorMode.Auto);
|
||
}
|
||
|
||
public void SetNormal()
|
||
{
|
||
Cursor.SetCursor(defaultCursor, Vector2.zero, CursorMode.Auto);
|
||
}
|
||
} |