- Home /
Raycast always returning true(SOLVED)
I'm having an issue with my raycast detection. I've tried to detect through both name and tag, but it ALWAYS returns true and runs whatever is in the if statement, even if it's not meeting the if statement requirements. I'm at a loss as to what is the issue here. Here is my code for my raycasting.
public Transform RaycastLocation;
private Ray ray;
private RaycastHit hit;
public void Start()
{
ray = new Ray(RaycastLocation.position, RaycastLocation.forward);
}
public void Update()
{
if(Physics.Raycast (ray, out hit, 500))
{
if(hit.transform.name == "Duck");
{
Debug.Log(hit.transform.name);
hit.collider.gameObject.SetActive(false);
}
}
Debug.DrawLine (ray.origin, hit.point);
}
You've named your public transform RaycastLocation. Why not something safer like raycastLocation? And it seems that you are running a function while checking "if" the first time. Line 14. if(Physics.Raycast...)
Should be Physics.Raycast...
Your code seems correct, are you 100% sure you are not meeting the 'if' requirements?
Try placing this script in a fresh new scene and test.
Are you sure, that the ray does not look always in the same direction? Try putting the line in the Start() function into Update().
You could try checking which object the raycast hits by adding Debug.Log(hit.transform.name) after raycasting. Also as a side note it's recommended to use raycast inside FixedUpdate ins$$anonymous$$d of Update.
try to see if you don't have it n the wrong guy:
if(Physics.Raycast (ray, out hit, 500))
{
// Did you add the script on the wrong object
Debug.Log(name);
if(hit.transform.name == "Duck");
{
Debug.Log(hit.transform.name);
hit.collider.gameObject.SetActive(false);
}
}
Answer by Baskyn · Apr 12, 2015 at 11:20 PM
Ok, I finally figured it out everybody! At the end of line 16, I had an ';', and it was not running properly. I remove it and it worked! Thanks everybody for your help!
Jesus, I can't believe I wasted a half of an hour on that...
Your answer
Follow this Question
Related Questions
C# raycast shooting script broken 1 Answer
Having a RaycastHit event create a component? 1 Answer
Trouble with checking Raycast 1 Answer
Multiple Cars not working 1 Answer