raycast with multiple layers

In my game I have a radius that when it hits a particular layer must perform a certain action. How can I say that he must behave in other ways when he hits other layers? I wanted to avoid another “if”

    public bool hasHit()
    {
       
        RaycastHit hit;
        if (Physics.Raycast(this.transform.position, this.transform.right, out hit, 0.2f, current))
        {
           
            //TODO
            return true;

        }
        else return false;
    }

I think you mean you want to avoid doing multiple Physics.Raycast() calls. You’ll need to use multiple IFs pretty much anyway you go, but an IF is not a problem.

The Raycasthit (the hit variable in your case) has information you can use. hit.transform will get you the Transfrom of what you hit. And the Transform has a gameObject property which will get you GameObject. And of course a GameObject has a layer property. :slight_smile:

So:

if(hit.transfrom.gameObject.layer == 2) {
  // Do something
}

You can also use a switch/case, of course.

2 Likes