Created
October 14, 2018 03:34
-
-
Save fuqunaga/036b8397f67217b04b693e5a7ba373c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class GUIOutSideDraggableSample : MonoBehaviour { | |
public Vector2 mousePos; | |
Vector2 boxSize = new Vector2(100f, 100f); | |
GUIStyle whiteBoxStyle; | |
private void Awake() | |
{ | |
whiteBoxStyle = new GUIStyle("box"); | |
whiteBoxStyle.normal.background = Texture2D.whiteTexture; | |
} | |
void OnGUI() | |
{ | |
using(new GUILayout.HorizontalScope()) | |
{ | |
GUILayout.Label("x"); | |
GUILayout.TextField(mousePos.x.ToString()); | |
} | |
using (new GUILayout.HorizontalScope()) | |
{ | |
GUILayout.Label("y"); | |
GUILayout.TextField(mousePos.y.ToString()); | |
} | |
// 可動範囲のBox | |
GUILayout.Box("", GUILayout.Width(boxSize.x), GUILayout.Height(boxSize.y)); | |
// BoxのRect取得 | |
var rect = GUILayoutUtility.GetLastRect(); | |
// コントロールID取得 | |
var controlID = GUIUtility.GetControlID(FocusType.Passive); | |
var ev = Event.current; | |
var eventType = ev.GetTypeForControl(controlID); | |
// イベントタイプ別処理 | |
switch(eventType) | |
{ | |
case EventType.MouseDown: | |
{ | |
if ( rect.Contains(ev.mousePosition)) | |
{ | |
GUIUtility.hotControl = controlID; | |
} | |
} | |
break; | |
case EventType.MouseUp: | |
{ | |
if ( GUIUtility.hotControl == controlID) | |
{ | |
GUIUtility.hotControl = 0; | |
} | |
} | |
break; | |
} | |
// このGUIがコントロール中の処理 | |
if ( ev.isMouse && (GUIUtility.hotControl == controlID)) | |
{ | |
mousePos = Rect.PointToNormalized(rect, ev.mousePosition); | |
// 他のGUI処理を無効化 | |
ev.Use(); | |
} | |
GUI.Box(new Rect(Rect.NormalizedToPoint(rect, mousePos), Vector2.one), "", whiteBoxStyle); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment