Detecting a certain object tag with ray casting

I am trying to write a script to put on my enemies, which will use ray casting to identify if the player is within range.

I currently have a working ray casting system, however it does not discriminate between my player and other objects. Is there a way to check the tag of the object the ray is hitting?

void enemySight()
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
       
        Vector3 forward = transform.TransformDirection(Vector3.forward) * 20;//For testing
        Debug.DrawRay(transform.position, forward, Color.green);//For testing
       
        //If enemy contacts an object (ie player)
        if (Physics.Raycast (transform.position, fwd, 20) && tag == "Player")//the 2nd condition is not working
        {
                  //Do something
        }
}

Yep definitely. You just need to add hit info about the target hit, like this:

void enemySight()
        {
            Vector3 fwd = transform.TransformDirection(Vector3.forward);
            Vector3 ray = transform.TransformDirection(Vector3.forward) * 20;//For testing
            RaycastHit hit;
          
            if (Physics.Raycast(transform.position, fwd, out hit, 100))
            {
                if(hit.transform.tag == "Player")
                {
                    // Do Something
                }
            }
        }

Raycasthit = http://docs.unity3d.com/ScriptReference/RaycastHit.html

1 Like

That makes sense.

When I try implementing it like this, my enemy stops moving once the ray hits the player, and I get a NullReferenceException: Object reference not set to an instance of an object at line 9 of the code above ^^^

Edit: I misspoke, that seems to be working fine after changing the arguments of the 1st if statement :smile:

Thank you for the feedback!

1 Like