EditorPrefs
Unity编辑器为开发者提供了类似PlayerPrefs的数据保存方式EditorPrefs。EditorPrefs是适用于编辑器模式,而PlayerPrefs适用于游戏运行时。
示例代码
bool currentValue = EditorPrefs.GetBool(key, false);
bool newValue = GUILayout.Toggle(currentValue, label);
EditorPrefs.SetBool(key, newValue);
编辑器模式下获取鼠标坐标与点击
使用Event.current.mousePosition 获取鼠标坐标。
通过Event.current.type 获取点击类型。
示例代码
if(Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag)
DoSomething();
输入类型有如下几种。
public enum EventType
{
MouseDown = 0,
mouseDown = 0,
MouseUp = 1,
mouseUp = 1,
MouseMove = 2,
mouseMove = 2,
MouseDrag = 3,
mouseDrag = 3,
KeyDown = 4,
keyDown = 4,
KeyUp = 5,
keyUp = 5,
ScrollWheel = 6,
scrollWheel = 6,
Repaint = 7,
repaint = 7,
Layout = 8,
layout = 8,
DragUpdated = 9,
dragUpdated = 9,
DragPerform = 10,
dragPerform = 10,
Ignore = 11,
ignore = 11,
Used = 12,
used = 12,
ValidateCommand = 13,
ExecuteCommand = 14,
DragExited = 15,
ContextClick = 16,
MouseEnterWindow = 20,
MouseLeaveWindow = 21
}
编辑器模式下鼠标坐标转换屏幕坐标
编辑器模式下坐标系是左上角为原点,而且实际的屏幕坐标是Event.current.mousePosition 坐标的两倍,如果使用编辑器模式下的鼠标坐标需要转换坐标。
Camera camera = SceneView.currentDrawingSceneView.camera;
Vector3 mousePosition = Event.current.mousePosition * 2;
mousePosition = new Vector3(mousePosition.x, camera.pixelHeight - mousePosition.y);
其他
在scene场景中不会点击选中物体。
HandleUtility.AddDefaultControl (GUIUtility.GetControlID (FocusType.Passive));
使用HideFlags 隐藏或者不可编辑目标。
obj.hideFlags = HideFlags.HideInHierarchy;
_myTarget.transform.hideFlags = HideFlags.NotEditable;
OnSceneGUI 使编辑器在场景视图中处理事件。
private void OnSceneGUI()
{
List<Mode> modes = EditorUtils.GetListFromEnum<Mode>();
List<string> modeLabels = new List<string>();
foreach (Mode mode in modes)
{
modeLabels.Add(mode.ToString());
}
Handles.BeginGUI();
GUILayout.BeginArea(new Rect(10f,10f,360f , 40));
_selectedMode = (Mode)GUILayout.Toolbar((int) _currentMode, modeLabels.ToArray(), GUILayout.ExpandHeight(true));
GUILayout.EndArea();
Handles.EndGUI();
}
效果图 SceneView.currentDrawingSceneView.in2DMode = true; 切换为2D视图。
GUI.FocusControl(""); 取消Editor界面焦点。
Editor.CreateEditor(temp).DrawDefaultInspector(); 在当前Inspector界面显示目标脚本的Inspector。
|