纳金网

标题: [unity3d脚本]编辑器的使用方法一(脚本转控件) [打印本页]

作者: 驰骋的风    时间: 2013-3-2 09:54
标题: [unity3d脚本]编辑器的使用方法一(脚本转控件)
Unity内置的编辑器,顾名思义就是在编辑状态下使用的,是用来提高开发效率的,当开发者在开发过程中需要对大量资源执行相似操作的时候,就可以使用编辑器来减少这种重复工作带来的开销,这里用到了UnityEditor命名空间。

今天说到的是编辑器的一种用法:将脚本的编辑拓展成控件,即在Inspector视口中不仅仅是对脚本中的共有变量进行编辑,还可以通过GUI,对脚本进行复杂的操作,以达到节省编辑数据时间的目的。


实现方法: 先写一个控件脚本(Control), 作为目的脚本,即要对物体进行的操作,将Control挂到目的物体上;再创建一个脚本(EditorControl), 用来编辑Inspector中的操作,查看Control在Inspector视口下的编辑栏。

EditorControl的写法:
复制代码using UnityEngine;using System.Collections;using UnityEditor;
[CustomEditor(typeof(Control))]public class EditorControl : Editor {
    // Use this for initialization    void Start (){    }        // Update is called once per frame    void Update (){    }
    Control control;    void OnEnable()    {        control = (Control)target;    }
    public override void OnInspectorGUI()    {        base.OnInspectorGUI();        if (GUILayout.Button("please",GUILayout.Width(50f)))        {            control.pref += 1;        }    }}
该脚本中有用的地方:
1.引用了UnityEditor命名空间;
2.定义的编辑器所编辑的脚本类型是Control类型 ( [CustomEditor(typeof(Control))] );
3.继承自Editor而不是Monobehaviour;
4.OnEnable方法,当物体激活的情况下执行;
5.OnInspectorGUI 这个虚方法需要重写,并且在这个方法下编写的GUI组件,将会呈现在Inspector视口下,从而达到我们要的效果。重点是base.OnInspectorGUI();这句,如果没有这句,Inspector中只会显示OnInspectorGUI()里的GUI元素,不会显示Control里的public变量;如果有这句,既会显示共有变量又会显示OnInspectorGUI()里的GUI元素。

这里我用了个简单的例子,Control的代码如下:

复制代码using UnityEngine;using System.Collections;
public class Control : MonoBehaviour {
    public int pref=3;
    private float pref2;
    // Use this for initialization    void Start ()    {    }}
在Inspector下看到的效果如下:


每点击一次please,pref+1.
更多复杂的GUI元素(如slider等),大家可以查看帮助文档。
转载于unity3D圣典论坛,原作者:ljz0225




欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5