通过指向对象来获取对象名称 Unity Raycast
Posted
技术标签:
【中文标题】通过指向对象来获取对象名称 Unity Raycast【英文标题】:Getting objects name by pointing on it Unity Raycast 【发布时间】:2021-02-21 06:31:27 【问题描述】:我想打印我指向的对象女巫的名称(使用 crosshari)。我写了一些脚本,允许我通过查看对象来突出显示它(包括在下面)。你能告诉我如何添加一行代码吗(打印我指向的对象的名称)?
1.SelectionManager
`public class SelectionManager : MonoBehaviour
[SerializeField] private string selectableTag = "Selectable";
private ISelectionResponse _selectionResponse;
private Transform _selection;
private void Awake()
_selectionResponse = GetComponent<ISelectionResponse>();
private void Update()
if (_selection != null) _selectionResponse.OnDeselect(_selection);
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
_selection = null;
if (Physics.Raycast(ray, out var hit))
var selection = hit.transform;
if (selection.CompareTag(selectableTag) || (selection.CompareTag("Stool_square1")))
//string name = gameObject.name;
//print(name);
_selection = selection;
if (_selection != null) _selectionResponse.OnSelect(_selection);
`
2.OutlineSelectionResponse
using UnityEngine;
public class OutlineSelectionResponse : MonoBehaviour, ISelectionResponse
public void OnSelect(Transform selection)
var outline = selection.GetComponent<Outline>();
if (outline != null) outline.OutlineWidth = 2;
public void OnDeselect(Transform selection)
var outline = selection.GetComponent<Outline>();
if (outline != null) outline.OutlineWidth = 0;
3.ISelectionResponse
using UnityEngine;
internal interface ISelectionResponse
void OnSelect(Transform selection);
void OnDeselect(Transform selection);
【问题讨论】:
无关提示:您应该针对图层蒙版进行光线投射。您当前的代码检查会针对场景中可能很慢的任何对撞机进行检查。 Raycast 函数有一个重载,它接受一个图层蒙版并检查给定图层中对撞机的命中。 【参考方案1】:试试hit.collider.name
之类的东西
【讨论】:
以上是关于通过指向对象来获取对象名称 Unity Raycast的主要内容,如果未能解决你的问题,请参考以下文章
Unity 怎么获取场景中顶级节点的所有GameObject