LoginSignup
3
4

More than 5 years have passed since last update.

UnityEventのインスペクタチェック方法

Last updated at Posted at 2015-11-14

UnityEventに、インスペクタ上でイベントが適切にアサインされているかを判断するコードです。
UnityEventにアサインされたイベントがない場合にエラーを出してくれるので、
リンク切れ時なんかに素早く気づくことができます。

チェック項目は3つ。
1. PersistentEventCountが適切な数であるか。
2. GetPersistentTargetがnullでないか。
3. GetPersistentMethodNameが空でないか。

例えば、unityEventという変数に1つのイベントを登録し、
その中にちゃんとイベントがアサインされていることを
Awakeで確認する場合、以下のようになります。

UnityEventCheck.cs

public UnityEvent unityEvent;

void Awake()
{
    //UnityEventを使う時のエラーチェック
    // (1) PersistentEventCountが1であることを確認(この例では0であってもいけないし、2以上であってもいけない)
    if (unityEvent.GetPersistentEventCount() != 1)
        Debug.LogError("PersistentEventCount muse be 1 !", transform);
    else
    {
        Debug.Log("PersistentEventCount is " + unityEvent.GetPersistentEventCount().ToString());

        // (2) GetPersistentTarget(0)がnullでないことを確認
        if (unityEvent.GetPersistentTarget(0) == null)
            Debug.LogError("Persistent Target is null!", transform);
        else
        {
            Debug.Log("PersistentTarget' name is " + unityEvent.GetPersistentTarget(0).name);

            // (3) GetPersistentMethodName(0)が空でないことを確認
            if (string.IsNullOrEmpty(unityEvent.GetPersistentMethodName(0)))
                Debug.LogError("PersistentMethodName is NullOrEmpty !", transform);
            else
                Debug.Log("PersistentMethodName : " + unityEvent.GetPersistentMethodName(0));
        }
    }
}

このエラーチェックはUnityEngine.UI.ButtonのonClickなどにも利用できます。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4