通过反射调⽤Unity编辑器提供的各种功能
暂住证和居住证的区别Unity编辑器功能丰富易上⼿,其实编辑器提供的⼤多数菜单操作,在代码⾥⾯都是能够找到对应接⼝的,但是这些接⼝都没有对我们开放,怎么办?
很简单,直接使⽤反射调⽤即可。
⾸先使⽤Reflector或ILSpy将UnityEditor和UnityEngine进⾏反编译(有源码的可以直接查看源码更好),然后在⾥⾯找你需要的功能即可,unity的底层代码命名是⾮常规范的,多数功能都能直观的找到:
下图中是Hierarchy视图中⼀些操作函数,怎么样,是不是很直观:
怎么调⽤这些函数呢,下⾯展⽰了static function和member function的调⽤⽅式,参考着⽤即可:
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class DIYEditor : EditorWindow
{
private static EditorWindow window;
[MenuItem("DIY/SelfEditor")]
public static void Execute()
{
搜肠刮肚的意思
if (window == null)
window = (DIYEditor)GetWindow(typeof(DIYEditor));
window.minSize = new Vector2(300, 300);
window.Show();
}
private void OnGUI()
{
if (GUILayout.Button("Project.DuplicateSelectedAsts", GUILayout.Height(50)))
{
ProjectDuplicate();
}
if (GUILayout.Button("Hierarchy.DuplicateSelectedAsts", GUILayout.Height(50)))
{
HierarchyDuplicate();
}
if (GUILayout.Button("GameView.SizeSelection", GUILayout.Height(50)))
{
SetGameView(1);四方协议
}
}
// 拷贝Project视图中的某个Prefab
private void ProjectDuplicate()
{
var type = typeof(Editor).Asmbly.GetType("UnityEditor.ProjectWindowUtil");
var duplicate = type.GetMethod("DuplicateSelectedAsts",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
过期奶粉能喝吗
兔拼音duplicate.Invoke(null, null);
}
思娇
// 拷贝Hierarchy视图中的某个Prefab,优点:(1)速度快(2)保持引⽤关系。在代码中Instantiate会丢失引⽤,并且速度很慢private void HierarchyDuplicate()
{
var type = typeof(Editor).Asmbly.GetType("UnityEditor.SceneHierarchyWindow");
写一篇日记
var window = EditorWindow.GetWindow(type);
var duplicateSelectedFunc = type.GetMethod("DuplicateGO",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
duplicateSelectedFunc.Invoke(window, null);
}
// ⼿动设置Game视图的分辨率,可以⽤来在编辑态下动态改变runtime分辨率
public static void SetGameView(int index)
{
var type = typeof(Editor).Asmbly.GetType("UnityEditor.GameView");
var window = EditorWindow.GetWindow(type);
var SizeSelectionCallback = type.GetMethod("SizeSelectionCallback",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); SizeSelectionCallback.Invoke(window, new object[] { index, null });
}
}
人类进步的阶梯 总之,编辑器功能强⼤,皆能为我所⽤,⽅法就是反射,以上!