Anas
Anas

Reputation: 25

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);
    }

}

}

My gaurd moves and when the player comes inside raycast, the GUI appear but name does not identify

everything works except "hit.collider.gameObject.name" Unity gives error that "object reference not set to an instance of an object"

please have a look i am new in Unity and C#

Upvotes: 0

Views: 2572

Answers (1)

Unai
Unai

Reputation: 436

The problem is that you do not have access to hit variable, because you are not storing it, you are only saving it in each iteration. A simple solution to that is to store the hit which makes playerInView = true;.

Something like this modifications to your Update() and OnGUI() methods must works;

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);
  }
}

Don't mind asking me any doubt you have about my approach.

Upvotes: 2

Related Questions