How to ignore a raycast collision with a particular object?

I have a Raycast and there can be multiple objects in front of the object that casts the ray.

I want to ignore some of the objects, say object "A" (tag). In the below situation, I want the Raycast to hit to the object "B" (tag):

Player Raycast ---- "A" ---- "B" —>

I have seen some answers including “layers”. I have no idea if they are necessary in this situation, and I don’t know how to use them or what they are, either.

How am I supposed to do this?

Just select Layer “Ignore raycast” for the particular object to not affect your raycast so the u can find the object behind it.

You want to use layers. Here is a reference page that explains layers:

Alternately you can use Physics.RaycastAll(), and then sort through the unsorted list of hits.

Using layers is more efficient. RaycastAll() is more flexible since you can setup specific criteria.

If you have a reference to the specific object, instead of creating layers or checking all hits, you can just temporarily disable the object’s collider for the raycast, then re-enable it.

From the docs:

RaycastHit[] hits = Physics.RaycastAll( transform.position , transform.forward , 100.0F );

One thing that can be confusing about Raycasts when you first encounter them: hits will be a variable of all things you hit, you can access the hit object itself from the hit.

The other concepts that are confusing with Raycasts are the out variable (which basically assign the response to the out var even though it is a parameter) and the QueryTriggerInteraction which simply tells the Raycast to ignore Triggers and can be set with QueryTriggerInteraction.Ignore. The default behavior is to include triggers so you only need that if you want to remove triggers from the Raycast.

[SerializeField] Transform _targetTransform = null;// target assigned in inspector 
[SerializeField] LayerMask mask;// set in inspector

RaycastHit[] hits = Physics.RaycastAll( transform.position , transform.forward , 100.0f , mask );
for( int i=0 ; i<hits.Length ; i++ )
    RaycastHit hit = hits[i];
    if( hit.transform==_targetTransform )
        // Look for a specific transform instance

    // Or get a specific Component
    Ship theShipWeHit = hit.transform.GetComponent<Ship>();
    if( theShipWeHit!=null )
        // Found something with a specific script, such as Health or whatever
    // Or get a specific Tag
    if( hit.transform.gameObject.CompareTag("Tag") )
        // Found something with a given tag.