- Home /
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.
Comment
Best Answer
Answer by demilp · May 12, 2013 at 03:50 PM
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.
You just need to check for != 0 rather than bothering to do the == 1 << c.gameObject.layer
Your answer
Follow this Question
Related Questions
using IsTouchingLayer without collision 0 Answers
How to achieve this basic physics effect? Detect when to change layers 2 Answers
How does Raycast layer mask work? 1 Answer
LayerMask is incorrect 1 Answer