OnMouseOver Distance Measuring

Sorry in advance if this is an issue that’s been solved before, I haven’t found a solution that works for me. I’m currently trying to implement text elements as descriptions for game objects using the OnMouseOver component in C#. Basically, if the player looks directly at the GameObject with this script it should enable a GUI element with the description. The problem is that the distance it can measure from the camera to the GameObject is infinite. If anybody can figure out a simple way to measure the distance from the camera to the Object and limit it to a specific amount that would be great! Here is the script:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class OnMouseUI : MonoBehaviour {

public GameObject Text;

public void OnMouseOver()

public void OnMouseExit()


I assume you have the script attached to your object so the simple way to get the distance is to use Vector3.Distance after getting the camera’s position like this

Transform camera = Camera.main.transform;
float dist = Vector3.Distance(camera.position, transform.position); //This is your distance

You can then limit the distance to a certain value as you wish using an if statement. Good luck!