(九)独立Inspector属性——如限制属性值范围

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

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

数据代码:

using UnityEngine;
using System.Collections;

/// <summary>
/// 特性,设置最大值和最小值。和渲染Drawer结合,限制属性的值的范围
/// </summary>  
public class MyTestAttribute : PropertyAttribute {
 
	public int max;
	public int min;
 
	public MyTestAttribute(int a, int b){
		min =a;
		max =b;
	}
}
 

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

 
using UnityEditor;
using System.Collections.Generic;
using UnityEngine;
 
 
[CustomPropertyDrawer(typeof(MyTestAttribute))]
public class MyTestDrawer : PropertyDrawer {
 
 
	public override void OnGUI (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;
 
public class Game : MonoBehaviour {
 
	[MyTestAttribute(0,100)]    // 设置特性限制,值为0到100
	public int intValue = 0;
}
 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值