UnityEvent は実行時に追加のプログラミングやスクリプト設定を必要とせずに、編集時から保持される駆動コールバックをユーザーが使用できるようにする方法です。
UnityEvent は以下のような場合に便利です。
コンテンツ駆動コールバック
分離システム
永続コールバック
事前設定コールイベント
UnityEvent
はどの MonoBehaviour
にも加えることができ、標準の .NET デリゲートのようにコードから実行することができます。UnityEvent
が MonoBehaviour
に加えられるときインスペクターに表示され、永続コールバックも加えることができます。
UnityEvent は、標準のデリゲートと同様の制限があります。つまり、ターゲットである要素に対するリファレンスを保持し、収集ターゲットがガベージコレクションされることを阻止します。ターゲットとして UnityEngine.Object を保有している場合、ネイティブ表現は消え、コールバックは呼び出されません。
エディターからコールバックを設定するために、いくつかの必要なステップがあります。
スクリプトには必ず UnityEngine.Events
をインポート/使用してください。
コールバックのスロットを加えるために + アイコンを選択します。
コールバックを受け取りたい UnityEngine.Object を選択します(これにはオブジェクトセレクターを使用することができます)。
呼び出したい関数を選択します。
イベント用に、一つ以上のコールバックを追加できます。
インスペクターから UnityEvent
を設定する場合、サポートされている関数が 2 つあります。
デフォルトで MonoBehaviour
の UnityEvent
は動的に void 関数をバインドします。UnityEvent は 4 つまで引数を伴う関数バインドをサポートしていますので、これは動的実行のケースである必要はありません。これを実行するために、複数の引数をサポートするカスタム UnityEvent
クラスを定義する必要があります。これは以下のように、本当に簡単にできます。
[Serializable]
public class StringEvent : UnityEvent <string> {}
このインスタンスをベースの UnityEvent
の代わりにあなたのクラスに加えることで、コールバックを動的に文字列関数と結びつけることを可能にします。
これは、‘string’ を引数として Invoke()
関数を呼び出すことで実行することができます。
UnityEvent はジェネリック定義で最大 4 つの引数を定義することができます。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.