赞
踩
创建属性
using System.Collections; using System.Collections.Generic; using UnityEngine; //这个脚本 不放在 Editor下 namespace RunAndJump.LevelCreator { //自定义的属性 需要继承PropertyAttribute 而不是MonoBehaviour public class TimeAttribute : PropertyAttribute { public readonly bool DisplayHours; public TimeAttribute(bool displayHours=false) { DisplayHours = displayHours; } } }
创建属性绘制器 需放在Editor文件夹下
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace RunAndJump.LevelCreator { //绑定属性到属性绘制器 [CustomPropertyDrawer(typeof(TimeAttribute))] public class TimeDrawer : PropertyDrawer//自定义的属性绘制器 需要继承PropertyDrawer { //定义属性绘制器 绘制的区域范围 //属性绘制器不支持 EditorGUILayout //绘制高度 public override float GetPropertyHeight(SerializedProperty property, GUIContent content) { return EditorGUI.GetPropertyHeight(property) * 2; } //具体的绘制GUI的操作 public override void OnGUI(Rect position, SerializedProperty property, GUIContent content) { //判断属性绑定的变量类型 //如果是绑定在int上 if (property.propertyType == SerializedPropertyType.Integer) { property.intValue = EditorGUI.IntField(new Rect(position.x, position.y, position.width, position.height / 2), content, Mathf.Max(0, property.intValue)); EditorGUI.LabelField(new Rect(position.x, position.y + position.height / 2, position.width, position.height / 2) ,"",TimeConvert(property.intValue)); } else//如果不是int,报错 { EditorGUI.HelpBox(position,"使用Time属性"+content.text+"必须是int",MessageType.Error); } } private string TimeConvert(int totalSeconds) { //获取当前属性绘制器绑定的属性,在PropertyDrawer里的attribute提供了当前绑定的对象 TimeAttribute time = attribute as TimeAttribute; if (time != null) { if (time.DisplayHours) { int hours = totalSeconds / (60 * 60); int minutes = (totalSeconds % (60 * 60)) / 60; int seconds = totalSeconds % 60; //padleft 占位符 return string.Format("{0}:{1}:{2}(h:m:s)",hours,minutes.ToString().PadLeft(2, '0'), seconds.ToString().PadLeft(2, '0')); } else { int minutes = totalSeconds / 60; int seconds = totalSeconds % 60; return string.Format("{0}:{1}(m:s)", minutes.ToString().PadLeft(2, '0'), seconds.ToString().PadLeft(2, '0')); } } else { return "time is null"; } } } }
最后创建测试脚本,并挂载对象上
using System.Collections; using System.Collections.Generic; using UnityEngine; using RunAndJump.LevelCreator; public class TimeDrawerDemo : MonoBehaviour { //约定俗成的是 Attribute可以省略[TimeAttribute] [Time] public int TimeSeconds = 3600; [Time(true)] public int TimeShowHours= 3600; [Time] public float TimeShowError = 3600; }
可以看到如下结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。