Layers in Unity define which GameObjects can interact with different features and one another. They are most commonly used by Cameras to render only a part of the scene, and by Lights to illuminate only parts of the scene. But they can also be used by raycasting to selectively ignore colliders or to create collisions.
まず最初に、新しいレイヤーを作成し、それを ゲームオブジェクト に割り当てます。新しいレイヤーを作成するには、Tags & Layers ウィンドウ (Edit > Project Settings を開き、Tags and Layers カテゴリを選択) を開きます。
空の User Layer の中から新規レイヤーを作成します。ここではレイヤー 8 を選択することにします。
Now that you have created a new layer, you can assign the layer to one or more GameObjects.
Each GameObject can only be assigned one layer.
Tags and Layers ウィンドウで、Player レイヤーを Layer 8に割り当てます。
カメラのカリングマスクを使用して、特定の 1 つのレイヤーのオブジェクトのみをレンダリングできます。 そのためには、オブジェクトを選択的に描画するカメラを選択します。
Culling Mask プロパティーでレイヤーのチェックをつけたり外したりすることでカリングマスクの設定を変更することができます。
UI 要素はカリングされないことに注意してください。スクリーンスペースのキャンバスの子はカメラのカリングマスクの影響を受けません。
レイヤーを使用して、特定のレイヤーでレイキャストを行ったり、コライダーを無視することができます。 例えば 、Player レイヤーのみにレイキャストを行い、他のコライダーを無視することができます。
Physics.Raycast 関数はビットマスクを使用して、ビットごとにレイヤーを無視するかどうか判定することができます。 layerMask (レイヤーマスク)のすべてのビットが有効である場合は、すべてのコライダーと衝突します。 もし layerMask = 0 の場合、レイがコライダーに衝突することはありません。
int layerMask = 1 << 8;
// Does the ray intersect any objects which are in the player layer.
if (Physics.Raycast(transform.position, Vector3.forward, Mathf.Infinity, layerMask))
{
Debug.Log("The ray hit the player");
}
この逆を行いたい場合もあります。Player レイヤー以外のすべてのコライダーに対してレイキャストを行います。
void Update ()
{
// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection (Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection (Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection (Vector3.forward) *1000, Color.white);
Debug.Log("Did not Hit");
}
}
Raycast 関数に layerMask を渡さない場合、IgnoreRaycast レイヤーのコライダーのみ無視します。 レイキャストを行うときに一部のコライダーを無視するにはこれがもっとも簡単です。
2017–05–08 Page amended
カリングマスクの情報は Unity 2017.1 で更新