The question is answered, right answer was accepted
Detect specific game object with raycast and show UI when hit
Hello,
So I am trying to make a light switch ( among other things ) work using raycast. I made it work, but the problem is that I don't know how I can also show UI like a tool tip ("Press F to use") only when the mouse is over the game object (the light switch). The range works but when I added the text it shows everywhere. Is the raycast hitting everything that's in the mouse position range?
public GameObject lightSwitch;
public GameObject lightSource;
public Text text;
private bool isOn;
void Start()
{
lightSource.SetActive(false);
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, 1))
{
text.text = "PRESS 'F' TO USE";
if(Input.GetKeyDown(KeyCode.F) && !isOn)
{
isOn = true;
lightSource.SetActive(true);
}
else if(Input.GetKeyDown(KeyCode.F) && isOn)
{
isOn = false;
lightSource.SetActive(false);
}
}
}
Answer by RX187 · Apr 13, 2018 at 12:27 PM
Thanks for the info but I actually found a solution:
public GameObject lightSwitch;
public GameObject lightSource;
public Text text;
private bool isOn = false;
public Collider col;
void Start()
{
lightSource.SetActive(false);
col = GetComponent<Collider>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(col.Raycast(ray, out hit, 1 ))
{
text.text = "Press F to use";
if(Input.GetKeyDown(KeyCode.F) && !isOn)
{
isOn = true;
lightSource.SetActive(true);
}
else if(Input.GetKeyDown(KeyCode.F) && isOn)
{
isOn = false;
lightSource.SetActive(false);
}
}
else { text.text = null; }
}
Answer by tormentoarmagedoom · Apr 12, 2018 at 01:49 PM
Good day.
I recommend you to learn abaut Event Trigger system. You will see is super simple to use, and so more easy than using Raycasts. And was created exactly for what you need.
Is better for you to go in an look the tutorial, better than recieve a specific answer ofr an specific problem.
If helped, accept the answer and close the question! Bye!
Follow this Question
Related Questions
Is the customizable character tutorial still out there somewhere? 2 Answers
Unity 3D textbook / ebook 0 Answers
Learning resource for networking? 1 Answer
Looking for a turn-based strategy beginner's tutorial. 5 Answers
Tutorial level 1 Answer