在unity编辑器中,我们见到过编辑器的菜单栏,也见过一些插件导入unity编辑器后插件自己的菜单栏。
如下图:
本文讲如何才能够创建出一个菜单。
首先在project的assets里新建一个名为Editor的文件夹。
视频教程请关注:unity风雨路
注意:一定要放在assets这个根目录下。
第二步在这个文件夹中新建脚本。
例如我新建脚本ToolEditorMenu。
具体代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ToolEditorMenu : MonoBehaviour
{
//添加菜单栏
[MenuItem("紫龙/紫龙大侠")]
static void ShowWindowTool()
{
//EditorWindow.GetWindow(typeof(ToolEditorWindow));
EditorWindow.GetWindow(typeof(ToolEditorWindow));
}
//添加菜单栏用于打开窗口
[MenuItem("我的插件/工具/下一层工具")]
static void ShownextWindow()
{
//EditorWindow.GetWindow(typeof(ToolEditorWindow));
EditorWindow.GetWindow(typeof(nextwindow));
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
在该脚本中共有两个菜单。
一个是一个二级菜单,另个是三级菜单。
先说二级菜单,只有"紫龙/紫龙大侠"这两个级别的菜单。
//添加菜单栏
[MenuItem("紫龙/紫龙大侠")]
static void ShowWindowTool()
{
EditorWindow.GetWindow(typeof(ToolEditorWindow));
}
这段代码实现的效果如下:
而另个三级菜单的代码如下:
//添加菜单栏用于打开窗口
[MenuItem("我的插件/工具/下一层工具")]
static void ShownextWindow()
{
EditorWindow.GetWindow(typeof(nextwindow));
}
效果如下:
会看到在工具后面还有一层菜单。
EditorWindow.GetWindow(typeof(nextwindow));
这个方法是获取菜单window的方法。所以GetWindow的方法里面必须有内容。需要返回一个窗口的类型。
所以以上两句代码中的typeof 里的内容是我定义的两个类。
第一个类 是ToolEditorWindow,直接是继承了MonoBehaviour。这个类里面是空的。如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ToolEditorWindow : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
这样是无法获取到ToolEditorWindow这个窗口的。
获取菜单窗口的方法在后面nextwindow这个类:继续向下看
-另个nextwindow这个类。继承了Editorwindow。需要导入using UnityEditor;这个引用。
这个Editorwindow是unity系统内部提供的。
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class nextwindow : EditorWindow
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
继承Editorwindow后会这个菜单会获得一个窗体。
所以点击这个菜单后会获取到nextwindow这个窗口,弹出这个窗口。如下: