Unity3D研究院编辑器之独立Inspector属性(九)

转自:http://www.xuanyusong.com/archives/3680
Unity提供了强大的Editor功能, 我们可以很轻易的在EditorGUI中绘制任意的属性。比如我之前写的文章 http://www.xuanyusong.com/archives/2202

那么问题就来了,如果我有多属性想共用同一段自定义控件,那么这种方法我就需要在多份代码里绘制控件了OnInspectorGUI 这一节中我们需要用到两个全新的自定义属性PropertyAttribute和PropertyDrawer。 可以理解为一个是数据,一个是渲染。

数据代码:

using UnityEngine;
using System.Collections;
publicclassMyTestAttribute:PropertyAttribute{
publicintmax;
publicintmin;
publicMyTestAttribute(inta,intb){
min=a;
max=b;
}
}

渲染代码,如果你想做一些复杂的结构,直接在OnGUI里面插入代码即可。

using UnityEditor;
using System.Collections.Generic;
using UnityEngine;
[CustomPropertyDrawer(typeof(MyTestAttribute))]
publicclassMyTestDrawer:PropertyDrawer{
publicoverride voidOnGUI(UnityEngine.Rect position,SerializedProperty property,UnityEngine.GUIContent label)
{
MyTestAttribute attribute=(MyTestAttribute)base.attribute;
property.intValue=Mathf.Min(Mathf.Max(EditorGUI.IntField(position,label.text,property.intValue),attribute.min),attribute.max);
}
}

最后在需要用这个通用组件的代码上添加如下代码即可。

using UnityEngine;
using System.Collections;
publicclassGame:MonoBehaviour{
[MyTestAttribute(0,100)]
publicintintValue=0;
}

如下图所示,这个属性的渲染就已经完全独立出来了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容