Event Mouse not working correctly

Im working on a custom editor, and the problem is, a simple Event.MouseDown and Event.MouseUp isn’t working correctly at all.
Code:

using UnityEngine;
using UnityEditor;
using System;
using System.Collections;

[CustomEditor(typeof(Thing)), Serializable, InitializeOnLoad]
public class ThingEditor : Editor {

	void OnSceneGUI(){

		Event current = Event.current;
		
		Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); 

		if(current.type == EventType.MouseDown) {
			Debug.Log ("HI");
		}

		if (current.type == EventType.MouseUp) {
			Debug.Log ("BYE");
		}
	}
}

Its not even saying BYE when I want it to.

I don't know why your code isn't working because I never tried your approach, but I use if(Input.GetMouseButtonDown(0)) and Input.GetMouseButtonUp(0)) in one of my scripts and it works just fine. Maybe try that? Then again I just saw you're doing something with OnSceneGUI, that was for OnGUI..

The "Input" class is only used In-Game. When wanting to get input In-Editor, you have to use Event. Its weird that way.

1 Answer

1

Are you sure your ThingEditor is active? So you have a Thing selected? Otherwise it ofcourse won’t work.

If you want to handle all events you should subscribe an event to SceneView.onSceneGUIDelegate. Unfortunately the SceneView class is still not documented but is available since i can think back.

Next thing is InitializeOnLoad only loads the class at start. That will initialize the static members of the class. It won’t create an instance of this editor. An editor is ment to “edit” an object (the target). Unless you have selected such an object (in your case a “Thing”) there won’t be an instance of this editor.

To handle generic SceneView events you should only use static things. This should work:

[InitializeOnLoad]
public class SceneViewEventHandler : Editor
{
    // static constructor
    static SceneViewEventHandler()
    {
        SceneView.onSceneGUIDelegate += OnSceneGUI;
    }

    static void OnSceneGUI(SceneView aView)
    {
        Event current = Event.current;
        Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
        
        if(current.type == EventType.MouseDown)
        {
            Debug.Log ("HI");
        }
 
        if (current.type == EventType.MouseUp)
        {
            Debug.Log ("BYE");
        }
    }
}

Keep in mind that the onSceneGUIDelegate is called for each SceneView independently. If you want to refer to the scene view, use the parameter that is passed to the delegate.

If you plan more complicated editor extension you might want to download ILSpy and take a look into the UnityEditor.dll. It really helps to understand the system better.

Nope this did not work. Everything i coded works fine except Event for the mouse. It says hi when i press my mouse down, but doesn't say bye when i let go.

The newest code you posted worked beautifully! Thanks a bunch Bunny83!