UnityGameProjectsCode / NightwatchGame / PlayerLookingAt.cs
PlayerLookingAt.cs
Raw
using UnityEngine;

public class PlayerLookingAt : MonoBehaviour
{
    //check what the player is looking at with rays and return the info
    private string objectLookingAtName;
    private GameObject objectLookingAt;

    private void Update()
    {
        RaycastHit hit;
        Ray newRay = new Ray(transform.position, transform.forward * 100);

        if (Physics.Raycast(newRay, out hit))
        {
            if (hit.transform.gameObject.GetComponent<MeshRenderer>()) //if object is visible
            {
                objectLookingAtName = hit.transform.gameObject.name;
                objectLookingAt = hit.transform.gameObject;
            }
            else
                objectLookingAtName = null;
        }
    }

    public string GetObjectName()
    {
        if (objectLookingAtName != null)
            return objectLookingAtName;
        else
            return "";
    }

    public float GetDistanceToObject()
    {
        return Vector3.Distance(this.gameObject.transform.position, objectLookingAt.transform.position);
    }
}