Skip to content

Instantly share code, notes, and snippets.

@karljj1
Created October 8, 2019 13:33
Show Gist options
  • Save karljj1/6b3b136bba5134e801f0d4e926929187 to your computer and use it in GitHub Desktop.
Save karljj1/6b3b136bba5134e801f0d4e926929187 to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class ScreenDragTest : MonoBehaviour
{
public Vector2 ScreenPos = new Vector2(100, 100);
public bool ConstantRefresh;
}
class SquareDragger : MouseManipulator
{
private Vector2 m_Start;
protected bool m_Active;
public SquareDragger()
{
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse });
m_Active = false;
}
protected override void RegisterCallbacksOnTarget()
{
target.RegisterCallback<MouseDownEvent>(OnMouseDown);
target.RegisterCallback<MouseMoveEvent>(OnMouseMove);
target.RegisterCallback<MouseUpEvent>(OnMouseUp);
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<MouseDownEvent>(OnMouseDown);
target.UnregisterCallback<MouseMoveEvent>(OnMouseMove);
target.UnregisterCallback<MouseUpEvent>(OnMouseUp);
}
protected void OnMouseDown(MouseDownEvent e)
{
if (m_Active)
{
e.StopImmediatePropagation();
return;
}
if (CanStartManipulation(e))
{
m_Start = e.localMousePosition;
m_Active = true;
target.CaptureMouse();
e.StopPropagation();
}
}
protected void OnMouseMove(MouseMoveEvent e)
{
if (!m_Active || !target.HasMouseCapture())
return;
Vector2 diff = e.localMousePosition - m_Start;
target.style.top = target.layout.y + diff.y;
target.style.left = target.layout.x + diff.x;
e.StopPropagation();
}
protected void OnMouseUp(MouseUpEvent e)
{
if (!m_Active || !target.HasMouseCapture() || !CanStopManipulation(e))
return;
m_Active = false;
target.ReleaseMouse();
e.StopPropagation();
}
}
[CustomEditor(typeof(ScreenDragTest))]
class ScreenDragTestEditor : Editor
{
protected virtual void OnEnable()
{
System.Reflection.Assembly assembly = typeof( UnityEditor.EditorWindow ).Assembly;
System.Type type = assembly.GetType( "UnityEditor.GameView" );
var gameView = EditorWindow.GetWindow(type);
var myImage = new Image(){ image = Texture2D.whiteTexture, tintColor = Color.red };
gameView.rootVisualElement.Add(myImage);
var screenDrag = target as ScreenDragTest;
myImage.BringToFront();
myImage.style.width = 20;
myImage.style.height = 20;
myImage.style.top = screenDrag.ScreenPos.y;
myImage.style.left = screenDrag.ScreenPos.x;
var manipulator = new SquareDragger();
myImage.AddManipulator(manipulator);
}
}
@karljj1
Copy link
Author

karljj1 commented Oct 8, 2019

Just an example of how we can embed custom editor elements into the GameView

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment