using UnityEngine; using System.Runtime.InteropServices; public class HighlightManager : MonoBehaviour { // WebGL 平台的外部 JavaScript 调用 #if UNITY_WEBGL && !UNITY_EDITOR [DllImport("__Internal")] private static extern void NotifySelectedObject(string objectName); #else // 非 WebGL 或编辑器模式下的模拟实现 private static void NotifySelectedObject(string objectName) { Debug.Log($"NotifySelectedObject called with: {objectName}"); } #endif private static GameObject currentHighlightedObject; // 高亮颜色设置 [SerializeField] private Color highlightColor = Color.yellow; // 高亮宽度设置 [SerializeField] private float highlightWidth = 5f; // 拖动检测相关变量 private Vector3 mouseDownPosition; // 鼠标按下的位置 private const float dragThreshold = 5f; // 拖动的阈值(像素) void Start() { // 确保有Outline组件 Outline outline = gameObject.GetComponent(); if (outline == null) { outline = gameObject.AddComponent(); } // 设置Outline参数 outline.OutlineColor = highlightColor; outline.OutlineWidth = highlightWidth; outline.enabled = false; } void OnMouseDown() { // 记录鼠标按下时的位置 mouseDownPosition = Input.mousePosition; } void OnMouseUp() { // 检测鼠标抬起时的位置与按下时的位置的距离 if (Vector3.Distance(mouseDownPosition, Input.mousePosition) > dragThreshold) { return; // 如果拖动距离超过阈值,则认为是拖动,直接返回 } // 如果有之前高亮的对象,取消其高亮 if (currentHighlightedObject != null) { Outline previousOutline = currentHighlightedObject.GetComponent(); if (previousOutline != null) { previousOutline.enabled = false; } } // 再次点击取消高亮 if (currentHighlightedObject == gameObject) { currentHighlightedObject = null; NotifySelectedObject("empty"); return; } // 高亮当前对象 Outline outline = GetComponent(); outline.enabled = true; // 更新当前高亮对象 currentHighlightedObject = gameObject; // 通知JavaScript NotifySelectedObject(gameObject.tag); } }