- Home /
Why isn't this raycast working?
This raycast isn't changing the value I want it to. Any idea why?
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, range)){
if (hit.transform.tag == "Blue Cube"){
hit.collider.gameObject.transform.GetComponent<blueCube>().grabbed = true;
}
}
Answer by aldonaletto · Jul 31, 2013 at 01:31 AM
This should work - IF a "Blue Cube" object is in the center of the screen and inside the range and it has a collider, of course. Add debug lines like below to help understanding what's going on:
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, range)){
print("Hit "+hit.transform.name);
if (hit.transform.tag == "Blue Cube"){
hit.transform.GetComponent<blueCube>().grabbed = true;
}
}
Notice that any field of hit that references the hit object may be used in GetComponent.
Thank you. I had forgot to generate collision for the mesh. I had a collider on it but forgot to generate colliders in the import settings.
Answer by RPGstandard · Jul 31, 2013 at 01:27 AM
have you given your game object a rigidbody? If not It wont detect the collision
@RPGstandard - as you say, collisions require a Rigidbody on one of the two game objects. Raycast() are not collisions do not require a Rigidbody component.
Ah.. I was not aware of that, Ive still got a lot to learn on here as well. Thanks for taking the time to correct me
As @robertbu said, Raycast doesn't require a Rigidbody - but remember that the object must have a collider in order to be detected by Raycast.