当前位置: 移动技术网 > IT编程>开发语言>c# > Unity自定义编辑器界面(Inspector界面)

Unity自定义编辑器界面(Inspector界面)

2020年03月09日  | 移动技术网IT编程  | 我要评论

在开发的过程中,往往会需要在组件中添加一些按钮,用于执行一些自定义的操作。

例如你有一个组件a,里面有一个list<collider>,你想在这个list中存放当前scene中所有的碰撞体数据。那么你会在组件a中写一个方法find去遍历获取,一种情况你可以运行unity的时候在start方法中去执行find方法,如果你想不运行unity的情况下就获取到,那么可以使用[executeineditmode]标签,然后依旧在start方法中执行find方法。再或者就是这篇要介绍的自定义编辑器界面来处理。

首先我们简单的写个组件如下:

using unityengine;
 
public class test : monobehaviour
{
  public float speed;
  public int length;
 
  public void reset()
  {
    speed = 0;
    length = 0;
  }
}

我们在一个gameobject上添加该组件后,inspector界面的显示为

然后我们可以在editor目录下建一个新的cs脚本,用于自定义该组件inspector界面的显示,代码如下:

using unityeditor;
using unityengine;
 
//添加这个标签,可以选择多个拥有test组件的gameobject进行同时修改,否则会提示multi-object editing not supported
[caneditmultipleobjects]
 
//关联对应的monobehaviour类
[customeditor(typeof(test))]
public class testinspector : editor
{
  public override void oninspectorgui()
  {
    test test = target as test;
 
    //添加了这句,当你选中一个带有test组件的gameobject时,修改了属性,点击工具栏edit,会显示undo recordtest和redo recordtest用于撤销和重做
    //同时如果是在prefab中,加上这句,在修改了属性之后prefab会知道属性的变化,你可以apply或revert,否则prefab无法检测出。(5.3版本之前使用editorutility.setdirty(test);)
    undo.recordobject(test, "recordtest");
 
    //显示默认视图(即test的speed和length)
    base.oninspectorgui();
 
    //在默认视图下方添加一行
    editorguilayout.beginhorizontal();
    if (guilayout.button("button 1"))
    {
      //点击按钮触发
      debug.log("name:" + test.name);
 
      test.speed = 100;
 
      //通知prefab属性变化,5.3版本前使用下面这句,之后使用undo.recordobject
      //editorutility.setdirty(test);
    }
    if (guilayout.button("button 2"))
    {
      //targets 表示选中的多个组件
      foreach (object obj in targets)
      {
        debug.log("name:" + obj.name);
        test item = obj as test;
        item.reset();
      }
    }
    editorguilayout.endhorizontal();
 
    if (gui.changed)
    {
      //如果属性改变时调用
    }
  }
}

这样显示界面就会变为

这样我们就可以在不运行unity的情况下执行一些组件方法,方便使用。

一些需要注意的如[caneditmultipleobjects],undo.recordobject,editorutility.setdirty在代码中注释了,大家可以自己尝试看看对应的作用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网