- Home /
Raycast not working
void Update()
{
Ray ray = GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
print(hit.transform.name);
if (hit.distance <= 20 && hit.transform.CompareTag("Interactable"))
{
text.text = hit.transform.GetComponent<Interactable>().GetDescription();
actionGfx.SetActive(true);
print("hit");
}
else
{
actionGfx.SetActive(false);
text.text = "";
}
}
}
Code looks fine to me, but for some reason it is creating some issues. The Raycast is fine, and can hit objects and retrieve their names. Line 7 runs, and prints the correct name of the object. However, for some reason nothing else runs inside the if condition. I even replaced the "hit.distance <= 20 && hit.transform.CompareTag("Interactable")" with "5 < 7" and the results are the same. Does anyone have any idea why everything is being ignored? Comment/reply for any questions regarding this, thanks.
iam sure if you remove the distance check entirely, it works right?
Answer by pandatree12 · May 17, 2019 at 08:54 PM
Extracting the body of the Physics.Raycast conditon to a seperate method fixed the issue. Here's what it looks like now:
// Update is called once per frame
void Update()
{
Ray ray = GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
CheckRayValues(hit);
}
else
{
point.SetActive(false);
description.text = "";
}
}
// Raycast function
private void CheckRayValues(RaycastHit hit)
{
if (hit.distance <= 1.5 && hit.transform.CompareTag("Interactable"))
{
point.SetActive(true);
description.text = hit.transform.GetComponent<Interactable>().GetDescription();
print(hit.distance);
}
else
{
point.SetActive(false);
description.text = "";
}
}
Not sure what the difference between extracting the method and not makes, but I guess it was needed here.
Answer by JonnyHilly · May 17, 2019 at 05:02 AM
also print the distance on the same line as print(hot.transform.name) and print hit.transform.tag and you'll have a lot more information to figure out what is going wrong. Even easier... use the debugger and put a breakpoint on the print(hit.transform... line, and then just look at all the variables in the debugger and you'll see what it hit, how far, etc..... You can also step through one line at a time, to see if it goes inside the If... or not Check your tag name matches a real tag also (check the case sensitivity)
I checked and the tag of the object matches the one in the if condition exactly and I checked everything else too. I will still try what you said and let you know if I can figure anything out. Thanks
I was able to fix the issue buy just extracting the body of the Physics.Raycast condition to a separate method. Not sure why that was the case.