How do I use LayerMask to check collision?

I’m having a hard time trying to understand how to use LayerMask.

Here is my code:

using UnityEngine;
using System.Collections;

public class ReturnToPoolByCollision : MonoBehaviour {

	public PoolObject<GameObject> pO;
	public Weapon w;
	public LayerMask mask;
	
	void OnCollisionEnter(Collision c){
		if (c.gameObject.layer == Layers.CAR){;
			if (c.gameObject != w.weaponOwner.gameObject){
				pO.pool.ReturnObjectToPool(gameObject);
			}
		}else{
			if (c.gameObject.layer == Layers.STAGE){
				pO.pool.ReturnObjectToPool(gameObject);
			}
		}				
			
	}
}

What I’m trying to do is to make this class generic by working with a LayerMask instead of checking layer by layer individually.

1 Like

I figured out the solution.

using UnityEngine;
using System.Collections;

public class ReturnToPoolByCollision : MonoBehaviour {

	public PoolObject<GameObject> pO;
	public Weapon w;
	public LayerMask mask;
	
	void OnCollisionEnter(Collision c){
		if((mask.value & 1<<c.gameObject.layer) == 1<<c.gameObject.layer){
			if (c.gameObject != w.weaponOwner.gameObject){
				pO.pool.ReturnObjectToPool(gameObject);
			}	
		}	
	}
	
}

Thanks anyway.