(:3[kanのメモ帳]

個人ゲーム開発者kan.kikuchiのメモ的技術ブログ。月木更新でUnity関連がメイン。

(:3[kanのメモ帳]


本ブログの運営者kan.kikuchiが個人で開発したゲームです!

    

SceneView上でクリックした時などのイベントを取得する【Unity】【エディタ拡張】


このエントリーをはてなブックマークに追加



この記事でのバージョン
Unity 2018.4.8f1


はじめに

今回はタイトル通り今回はSceneView上でのイベントを取得する方法のご紹介です!

f:id:kan_kikuchi:20191022085706g:plain


なお、エディタを再生していても、いなくても取得出来ます。


Event.currentとSceneView.onSceneGUIDelegate

クリックなど、操作した時のイベントはEvent.currentで取得出来ます。

(発生したイベントの種類はEvent.current.typeで判別可能)


ただし、そのEvent.currentを参照するタイミングが重要

SceneView上のイベントを取得したい時はSceneView.onSceneGUIDelegateを使います。

using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]//ExecuteInEditModeを付ける事でOnEnableが再生していなくても実行されるようになる
public class NewBehaviourScript : MonoBehaviour {

  private void OnEnable() {
    //シーンビュー上のイベントを取得するため、メソッドを登録
    SceneView.onSceneGUIDelegate += OnOccurredEventOnSceneView;
  }

  //シーンビュー上でイベントが発生した
  private void OnOccurredEventOnSceneView(SceneView scene){
   //発生したイベントの種類をログで表示
    Debug.Log(Event.current.type);
  }
  
}
f:id:kan_kikuchi:20191022085706g:plain


ちなみにEditorApplication.updateを使うとEvent.currentは常にnullですし、

using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]//ExecuteInEditModeを付ける事でOnEnableが再生していなくても実行されるようになる
public class NewBehaviourScript : MonoBehaviour {

  private void OnEnable() {
    EditorApplication.update += Update;
  }

  private void Update() {
    var currentEvent = Event.current;
    if (currentEvent == null) {
      Debug.Log("Update : null");
      return;
    }
    
    Debug.Log($"Update : {currentEvent.type}");
  }

}
f:id:kan_kikuchi:20191022090045g:plain


OnDrawGizmosを使っても一部のイベントしか取得できません。

using UnityEngine;

[ExecuteInEditMode]//ExecuteInEditModeを付ける事でOnDrawGizmosが再生していなくても実行されるようになる
public class NewBehaviourScript : MonoBehaviour {

  private void OnDrawGizmos() {
    Debug.Log("OnDrawGizmos");
    
    var currentEvent = Event.current;
    if (currentEvent == null) {
      return;
    }
    
    Debug.Log($"OnDrawGizmos : {currentEvent.type}");
  }

}
f:id:kan_kikuchi:20191022091757g:plain