以下の例は、衝突関数からイベントを呼び出す方法を示しています。ここでは、それぞれ OnCollisionEnter と OnTriggerEnter を使用していますが、概念はすべての OnCollision 関数と OnTrigger 関数に適用されます。
他のコライダーに関連付けられたゲームオブジェクトの名前やタグなどのプロパティに基づいて、さまざまなイベントをトリガーするようにスクリプトを設定できます。例えば、一部のコライダーにイベントの生成を許可し、他のコライダーには許可しないというような場合に便利です。
以下の例では、このコライダーに触れた他のコライダーのタグが「プレイヤー」か「敵」かによって異なるメッセージを出力します。
using UnityEngine;
using System.Collections;
public class DoorObject : Monobehaviour
{
private void OnCollisionEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log ("The player character has touched the door.")
}
if (other.CompareTag("Enemy"))
{
Debug.Log ("An enemy character has touched the door!")
}
}
}
以下の例では、トリガーコライダーを使用してホバーパッドを作成します。トリガーコライダーは、ホバーパッドゲームオブジェクトのすぐ上に配置され、トリガー内のすべてのゲームオブジェクトに一定の上方向の力を加えます。
using UnityEngine;
using System.Collections;
public class HoverPad : MonoBehaviour
{
// define a value for the upward force calculation
public float hoverForce = 12f;
// whenever another collider is in contact with this trigger collider…
void OnTriggerStay (Collider other)
{
// …add an upward force to the Rigidbody of the other collider.
other.rigidbody.AddForce(Vector3.up * hoverForce, ForceMode.Acceleration)
}
}