Files
3d-qiaozha/Assets/SelectEdgeGlow.cs
2026-03-10 10:07:11 +08:00

60 lines
2.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine; // 引入 UnityEngine 命名空间,提供组件、物理、渲染等 API
public class SelectEdgeGlow : MonoBehaviour // 声明一个挂在场景物体上的组件类
{
public LayerMask pickLayers = ~0; // 可被射线点击的图层集合;~0 表示所有位为 1等价允许所有图层
public string highlightLayerName = "Highlight"; // 用于高亮渲染的专用图层名,需在 Project Settings → Tags and Layers 里创建
int hlLayer = 6; // 运行时把图层名转换成的图层索引
//Renderer last; // 上一次被选中的 Renderer用于单选时取消上一个
public GameObject lastObj;
public GameObject currentObj;
void Start() // Unity 生命周期函数,组件启用的第一帧调用
{
}
void Update() // 每帧调用,用于处理输入与选择
{
if (!Input.GetMouseButtonDown(0)) // 若这一帧没有按下鼠标左键
return; // 直接结束本帧逻辑
var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 从主相机通过鼠标位置发出一条射线
if (Physics.Raycast(ray, out var hit, 2000f, pickLayers) && hit.collider.CompareTag("Target")) // 做物理射线检测:最大 500 单位,只检测 pickLayers
{
//var r = hit.collider.GetComponentInParent<Renderer>(); // 从命中的 Collider 向上查找 Renderer兼容 Collider 在子节点
//if (r != null) // 命中并找到渲染器
//{
// if (last != null && last != r) // 如果之前有选中且不是同一个对象
// SetHighlight(last, false); // 先取消上一个,避免还原用错图层
// SetHighlight(r, true); // 再对当前命中的对象打开高亮
// last = r; // 记录当前为“上一个”
//}
if (lastObj = null)
{
currentObj = hit.collider.GetComponent<Transform>().gameObject;
currentObj.layer = 6;
}
if(lastObj != null)
{
currentObj = hit.collider.GetComponent<Transform>().gameObject;
currentObj.layer = 6;
lastObj.layer = 0;
}
lastObj = currentObj;
}
//else // 射线没有命中任何可选对象
//{
// if (last != null) // 若此前有选中
// SetHighlight(last, false); // 关闭它的高亮并还原图层
// last = null; // 清空记录
//}
}
}