コライダーイベントのスクリプト例
Example scripts for OnCollision and OnTrigger events. These example scripts demonstrate some potential uses for scripted collision interactions and events.
読み終わるまでの所要時間 3 分最終更新 1ヶ月前
以下の例は、衝突関数からイベントを呼び出す方法を示しています。ここでは、それぞれ と を使用していますが、概念はすべての 関数と 関数に適用されます。
OnCollisionEnterOnTriggerEnterOnCollisionOnTrigger例さまざまなゲームオブジェクトのプロパティに応じた異なるイベント
他のコライダーに関連付けられたゲームオブジェクトの名前やタグなどのプロパティに基づいて、さまざまなイベントをトリガーするようにスクリプトを設定できます。例えば、一部のコライダーにイベントの生成を許可し、他のコライダーには許可しないというような場合に便利です。
以下の例では、このコライダーに触れた他のコライダーのタグが「プレイヤー」か「敵」かによって異なるメッセージを出力します。
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) }}