- Home /
How can i get a layer's collision mask?
I want to cast a ray with the same collision properties that it would have, if it were an object on a specific layer. The raycast should hit anything that object would collide with, and ignore everything that object would pass through.
I can manually copy this information and hardcode it, but that seems wrong, especially since i'd have to update that if i change the collision settings later
Is there any script command where i can specify a layer, and it'll return a layermask for how that layer collides with others?
Answer by Baste · Feb 17, 2015 at 09:49 AM
There's a method named Physics.GetIgnoreLayerCollision(int layer1, int layer2). It returns true if layer1 and layer2 doesn't collide.
So to set up the layermask for your raycast, you would get the layer of your object, and then create a layermask with a for-loop:
int myLayer = gameObject.layer;
int layerMask = 0;
for(int i = 0; i++; i < 32) {
if(!Physics.GetIgnoreLayerCollision(myLayer, i)) {
layerMask = layermask | 1 << i;
}
}
That should give you the correct layermask.
that seems like a pretty roundabut way of doing things :/ i guess it'll do, but shouldn't this data be cached and retrievable somewhere?
You're right about it being roundabout, but you just have to do it once, in the start method:
private int layer$$anonymous$$ask;
void Start() {
int myLayer = gameObject.layer;
int layer$$anonymous$$ask = 0;
for(int i = 0; i++; i < 32) {
if(!Physics.GetIgnoreLayerCollision(myLayer, i)) {
layer$$anonymous$$ask = layermask | 1 << i;
}
}
}
and then when you raycast:
void DoTheRaycast(Vector3 direction, float length) {
RaycastHit hit;
if(Physics.Raycast(transform.position, direction, out hit, length, layer$$anonymous$$ask) {
Debug.Log("I hit: " + hit.collider);
}
}
Your answer
