Unity raycast 碰撞对象并在 GUI 上打印其名称

Unity raycast collide object and print its name on GUI

using UnityEngine;
using System.Collections;
public class GuardSample : MonoBehaviour 
{
FOV2DEyes eyes;
FOV2DVisionCone visionCone;
float speed = -5;
RaycastHit hit;


void Start() 
{
    eyes = GetComponentInChildren<FOV2DEyes>();
    visionCone = GetComponentInChildren<FOV2DVisionCone>();
}

void FixedUpdate()
{
    if (transform.position.x < -10 || transform.position.x > 10)
    {
        speed *= -1;
    }

    transform.position = new Vector3(transform.position.x + speed * Time.fixedDeltaTime, transform.position.y, transform.position.z);
}

bool playerInView = false;

void Update()
{
    playerInView = false;
    foreach (RaycastHit hit in eyes.hits)
    {
        if (hit.transform && hit.transform.tag == "Player")
        {
            playerInView = true;
        }
    }

}

void OnGUI()
{
    if (playerInView)
    {
        GUI.Box (new Rect (10, 10, 160, 60), "Title");
        GUI.Label( new Rect(10, 10, 160, 60), hit.collider.gameObject.name);
    }

}

}

我的 gaurd 移动,当玩家进入 raycast 时,GUI 出现但名称无法识别

一切正常,除了 "hit.collider.gameObject.name" Unity 给出错误 "object reference not set to an instance of an object"

请看一下我是 Unity 和 C# 的新手

问题是您无权访问命中变量,因为您没有存储它,您只是在每次迭代中保存它。一个简单的解决方案是存储使 playerInView = true;.

的命中

像这样对您的 Update() 和 OnGUI() 方法进行的修改必须有效;

RaycastHit hittenGo; // Declare up this variable

void Update()
{
  playerInView = false;
  foreach (RaycastHit hit in eyes.hits)
  {
    if (hit.transform && hit.transform.tag == "Player")
    {
        hittenGo = hit;
        playerInView = true;
    }
  }
}

void OnGUI()
{
  if (playerInView)
  {
    GUI.Box (new Rect (10, 10, 160, 60), "Title");
    GUI.Label( new Rect(10, 10, 160, 60), hittenGo.collider.gameObject.name);
  }
}

如果您对我的方法有任何疑问,请不要介意问我。