孙广东 2015、7、12
Unity的很多编辑器功能都是通过特性Attribute实现。
那么我们要自己扩展Inspector也是要自己写Attribute。
先说说为什么要这样做?
为了编写面向对象程序,封装特性 更优雅。下面的脚本使 属性 (即有 getter/setter 的成员) 的内容可以在Unity的Inspector上显示。
这样就可以保密类的 字段,并限制所有的外部访问,只能通过 属性 访问,
看看代码吧!
using System;
[AttributeUsage(AttributeTargets.Property)] public class ExposePropertyAttribute : Attribute {}
在 "Assets/Editor" 的脚本
using UnityEditor;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
public static class ExposeProperties
{
public static void Expose(PropertyField[] properties)
{
var emptyOptions = new GUILayoutOption[0];
EditorGUILayout.BeginVertical(emptyOptions);
foreach (PropertyField field in properties)
{
EditorGUILayout.BeginHorizontal(emptyOptions);
if (field.Type == SerializedPropertyType.Integer)
{
var oldValue = (int)field.GetValue();
var newValue = EditorGUILayout.IntField(field.Name, oldValue, emptyOptions);
if (oldValue != newValue)
field.SetValue(newValue);
}
else if (field.Type == SerializedPropertyType.Float)
{
var oldValue = (float)field.GetValue();
var newValue = EditorGUILayout.FloatField(field.Name, oldValue, emptyOptions);
if (oldValue != newValue)
field.SetValue(newValue);
}
else if (field.Type == SerializedPropertyType.Boolean)
{
var oldValue = (bool)field.GetValue();
var newValue = EditorGUILayout.Toggle(field.Name, oldValue, emptyOptions);
if (oldValue !