(:3[kanのメモ帳]

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

(:3[kanのメモ帳]


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

    

SceneViewでマウス(トラックパッド)のボタンを離した時のイベント(EventType.MouseUp)が発生しない時の対処法【Unity】【エディタ拡張】


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


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


はじめに

Unityエディタが再生してない時でもMonoBehaviourの各種メソッドが実行出来るExecuteAlways

シーンビューでイベントが発生した時を検知出来るSceneView.duringSceneGuiを組み合わせる事で

SceneViewでマウス(トラックパッド)のボタンを押した時を検知する事が出来ます。

using UnityEditor;
using UnityEngine;

[ExecuteAlways]//OnEnable等がUnityエディタを再生していなくても実行されるように
public class NewBehaviourScript : MonoBehaviour {

  private void OnEnable() {
    SceneView.duringSceneGui += OnScene;
  }

  private void OnDisable() {
    SceneView.duringSceneGui -= OnScene;
  }
  
  //シーン上でイベントが発生した
  private void OnScene(SceneView scene) {
    var currentEvent = Event.current;
    if (currentEvent == null) {
      return;
    }

    if (currentEvent.type == EventType.MouseDown) {//実行される
      Debug.Log($"マウスのボタン押した : 座標 {currentEvent.mousePosition}");
    }
    else if (currentEvent.type == EventType.MouseUp) {//実行されない
      Debug.Log($"マウスのボタン離した : 座標 {currentEvent.mousePosition}");
    }
  }

}


しかし、仕様かバグかは分からりませんが、なぜかマウスのボタンを離した時は検知出来ません。

今回はそんな時の対処法です。


対処法

早速対処法ですが、GUIUtility.GetControlIDでマウスのIDを取得し、



そのIDをHandleUtility.AddDefaultControlでデフォルトのコントロールに設定するだけ。



具体的には以下のような感じです。


private void OnScene(SceneView scene) {
  //これを追加
  HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

  var currentEvent = Event.current;
  if (currentEvent == null) {
    return;
  }

  if (currentEvent.type == EventType.MouseDown) {//実行される
    Debug.Log($"マウスのボタン押した : 座標 {currentEvent.mousePosition}");
  }
  else if (currentEvent.type == EventType.MouseUp) {//実行される
    Debug.Log($"マウスのボタン離した : 座標 {currentEvent.mousePosition}");
  }
}



参考