- Home /
Raycast object tag check?
I am trying to check if the raycast hits an object with the tag "Dynamic". I cant seem to figure out why the script I wrote doesnt work.
var hit : RaycastHit;
var Reach : float = 2.0;
var RayHit : boolean;
function Update () {
var fwd = transform.TransformDirection (Vector3.forward);
Debug.DrawRay(transform.position, fwd * Reach, Color.red);
if (Physics.Raycast (transform.position, fwd, Reach)&&hit.transform.gameObject.tag == "Dynamic") {
RayHit = true;
}
else {
RayHit = false;
}
}
Answer by aldonaletto · Sep 16, 2013 at 01:29 AM
You forgot to pass the hit structure to Raycast (you've got no errors because there exists such overload version of Raycast). Change the Raycast call to this:
if (Physics.Raycast (transform.position, fwd, hit, Reach) && hit.transform.tag == "Dynamic") {
Notice also that hit.transform already allows direct access to the property tag, thus you can just write hit.transform.tag instead of hit.transform.gameObject.tag.
The function is supposed to be
if (Physics.Raycast (transform.position, fwd, out hit, Reach) && hit.transform.tag == "Dynamic") {
not
if (Physics.Raycast (transform.position, fwd, hit, Reach) && hit.transform.tag == "Dynamic") {
Answer by Content1of_akind · Apr 21, 2019 at 08:29 PM
If you make a raycast with the name hit, then create an if statement like this to perform when a specific tag collides with the raycast hit. Cheers! If this answer is off topic then I'm sorry for the inconvenience.
if(hit.collider.tag == "TagName")
{
print("You touched the TagName, nice!");
}
Answer by Kenthria11 · Jun 23, 2017 at 10:42 AM
Including any var such as var RayHit : boolean;
gives error: The contextual keyword `var' may only appear within a local variable declaration
That's because old unity vas using local variables. Now, you can do <type> <name> = <value>;
For example var Reach : float = 2.0; becomes
float Reach = 2.0f;