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移动,当玩家进入光线投射时,GUI出现,但名称无法识别
一切正常,除了“hit.collider.gameObject.name” Unity给出错误“对象引用未设置为对象的实例”
请看看我是Unity和C#的新手
答案 0 :(得分:2)
问题是你没有访问命中变量,因为你没有存储它,你只是在每次迭代中保存它。一个简单的解决方案是存储生成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);
}
}
不介意问我对我的做法有任何疑问。