目录
1、Unity编辑器扩展介绍
Unity为开发者们提供了很方便的扩展功能,编辑器扩展主要可以用于在Unity界面中添加属于自己的菜单、插件。有时可以大大的提高开发效率。
用于编辑器扩展的脚本都放在Editor文件夹中,此文件夹中的资源不会在项目发布时候打包。
2、具体功能
在使用扩展功能时,需要引用UnityEditor命名空间
2.1、在菜单栏中添加扩展
在菜单栏中的扩展可以自己新创,也可以加在已有的菜单里面。
using UnityEditor; //编辑器的命名空间
public class Tools { //不需要继承MonoBehaviour
[MenuItem("MyTools/Test1")] //让其显示在菜单栏MyTools-Test1下,MyTest1方法表示要做的工作
//放在其下面的方法代表调用这个。上面写的是路径名字
static void MyTest1() //只有静态方法可以使用MenuItem属性
{
Debug.Log("扩展1");
}
}
[MenuItem("MyTools/Test1",false,1)]
第一个参数表示在菜单栏的位置
第二个参数下面会提到。
第三个参数表示优先级,默认为1000。优先级越大越靠下面,优先级相差>10时,会出现分隔符
2.2、为扩展事件添加快捷键
[MenuItem("MyTools/Test1 %t",false,11)]
在第一个参数后面加空格然后写要加的快捷键。
此例就代表快捷键为 Ctrl+t
% == Ctrl
# == Shift
& == alt
2.3、Hierarchy,Project视图中右键添加扩展
Hierarchy视图右键下的基本都是GameObject菜单第一层分割线之上的扩展。
那么只要把扩展放在第一层的分割线之上不就行了。
而优先级为11则刚好在第一层分割线的最后一个。
[MenuItem("GameObject/Test1",false,11)]
Project右键下的选项基本都在Assets目录下,添加方法同上。
2.4、使用Selection类选择游戏物体
Selection属于UnityEditor命名空间。
//静态方法,单个对象
GameObject go1 = Selection.activeGameObject;
//返回选择场景中的一个游戏物体或者预制体。未选择会报错返回none,选择多个会返回第一个。
Object object1 = Selection.activeObject;
activeObject:返回选择场景中的一个游戏物体或预制体、脚本等任意物体。未选择会报错返回none,选择多个会返回第一个。
Transform transform = Selection.activeTransform;
activeTransform:返回选择场景中的一个游戏物体。未选择会报错返回none,选择多个会返回第一个。
//静态方法,多个对象
GameObject[] gameObjects = Selection.gameObjects;
//返回GameObject类型数组,为选择场景中的多个游戏物体或者预制体。只会选择符合条件的,未选择则数组长度为0。
Object[] objects = Selection.objects;
//返回Object类型数组,为选择场景中的多个游戏物体或者任意资源。只会选择符合条件的,未选择则数组长度为0。
Transform[] transforms = Selection.transforms;
//返回transform类型数组,为选择场景中的多个游戏物体。只会选择符合条件的,未选择则数组长度为0。
2.5、Menuitem第二个参数
使用第二个参数时一般配合两个方法来使用。
[MenuItem("SelectionTest/Test1 _t", true, 1)]
static bool Test()
{
if (Selection.activeTransform == null)
return false;
return true;
}
[MenuItem("SelectionTest/Test1 _t",false,1)]
static void Test1()
{
Debug.Log(Selection.activeTransform.name);
}
第二个方法在未选择物体时,本来会报错none。
当使用第二个参数设为true时,只有当此函数返回为true,才会继续执行下面的函数。
那么当未选择物体时,第一个函数返回false,就不会再进行第二个函数。就避免了报错的情况。
注意:MenuItem里的游戏路径和名称必须都相同。
2.6、ContextMenu和ContextMenuItem
第一个类用于在组件的右键中添加扩展。
- 对系统组件添加扩展
[MenuItem("CONTEXT/Rigidbody/Clear")]
//CONTEXT(默认写法) , 组件名 , 扩展名
static void ClearMassGravity(MenuCommand cmd)
//MenuCommand是当前正在操作的组件对象。只要定义就行,系统会自动赋值
{
Rigidbody rgd = cmd.context as Rigidbody;
//MenuCommand.context为正在操作的组件对象
rgd.mass = 0;
}
- 对自定义脚本添加扩展
//
[ContextMenu("SetColor")]
void SetColor()
{
flashColour = Color.green;
}