- Home /
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()
{
Text.SetActive(true);
}
public void OnMouseExit()
{
Text.SetActive(false);
}
}
Answer by Anis1808 · Dec 05, 2019 at 12:06 AM
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!
Your answer
Follow this Question
Related Questions
How to double spirte/gameobject/prefab and control the result on those items? 0 Answers
Do something with GameObject with certain distance 1 Answer
How to prevent a script on a disabled object from firing? 0 Answers
How to access a game object from a different scene? 0 Answers
Calculating Scrolling GameObject x position scrolling pass another GameObject x postion (2D Game) 1 Answer