讲解如何在Unity的Inspector面板中用滑动条来控制变量的大小

首先,我们现在的需求是这样的,我定义了一个脚本,里面有一个int类型的变量,但是我想控制变量的大小在0到100之间,通过用滑动条的方式来控制。

其实这里的player HP 是我使用了unity自带的一个滑动条来读取的值

‘玩家魔法值’在代码中的定义是playerMP,,是我使用了自己自定义的一个方法来改的,看起来更直观

再次首先,我先说一下这个工程里一共有3个脚本,分别是:

(1)ValueRangeExample.cs

(2)MyRangeAttribute.cs

(3)MyRangeAttributeDrawer.cs

哎哎哎,你的字怎么分开了啊,打错了吧!!!

哈,没有打错,故意空行的,脚本(1)ValueRangeExample.cs我们是吧它挂载到了主摄像机的身上

(2)MyRangeAttribute.cs 和 (3)MyRangeAttributeDrawer.cs 哪里都没有挂载,他们两个是对[MyRangeAttribute(0,100)]功能的编写,看下面代码就懂啦~

(1)ValueRangeExample.cs:

using UnityEngine;using System.Collections;/// <summary>/// 脚本位置:挂载到主摄像机上/// 脚本功能:通过一个滑动条来控制变量值的大小/// 创建时间:2015.07.26/// </summary>public class ValueRangeExample : MonoBehaviour {// 【系统自带功能】// 这个Range是系统自带的一个滑动条模式的取值范围// 在Inspector会显示一个滑动条来控制变量,变量的名字默认读取它下面第一个可以执行的行的代码// 什么叫可以执行的行的代码。。。它下一行是注释的话就是不能执行的对吧。。。恩,就是这样。。。[Range(0,100)]public int playerHP;// ——————————————–// 【自己编写相同功能,并扩展可以定义文字】// MyRangeAttribute就是我们的第二个脚本// MyRangeAttribute是一个继承PropertyAttribute类的脚本[MyRangeAttribute(0,100,"玩家魔法值")]public int playerMP;}(2)MyRangeAttribute.cs

其实只是继承了PropertyAttribute类,什么功能都没有实现,功能的实现是在脚本(3)MyRangeAttributeDrawer.cs中

using UnityEngine;using System.Collections;/// <summary>/// 脚本位置:要求放在Editor文件夹下,其实不放也可以运行/// 脚本功能:实现一个在Inspector面板中可以用滑动条来控制变量的大小/// 创建事件:2015.07.26/// </summary>public class MyRangeAttribute : PropertyAttribute {// 这3个变量是在Inspector面板中显示的public float min; // 定义一个float类型的最大public float max; // 定义一个float类型的最大public string label; // 显示标签// 在脚本(1)ValueRangeExample定义[MyRangeAttribute(0,100,"玩家魔法值")]// 就可以使用这个功能了,但是为什么这里的string label = ""呢// 因为给了一个初值的话,在上面定义[MyRangeAttribute(0,100)]就不会报错了,不会提示没有2个参数的方法public MyRangeAttribute(float min, float max,string label = ""){this.min = min;this.max = max;this.label = label;}}(3)MyRangeAttributeDrawer.csusing UnityEngine;using System.Collections;using UnityEditor; // 引入Editor命名空间// 使用绘制器,如果使用了[MyRangeAttribute(0,100,"lable")]这种自定义的属性抽屉// 就执行下面代码对MyRangeAttribute进行补充[CustomPropertyDrawer(typeof(MyRangeAttribute))]/// <summary>/// 脚本位置:要求放在Editor文件夹下,其实不放也可以运行/// 脚本功能:对MyRangeAttribute脚本的功能实现/// 创建事件:2015.07.26/// </summary>// 一定要继承绘制器类 PropertyDrawerpublic class MyRangeAttributeDrawer: PropertyDrawer {// 重写OnGUI的方法(坐标,SerializedProperty 序列化属性,显示的文字)public override void OnGUI(Rect position, SerializedProperty property, GUIContent lable){// attribute 是PropertyAttribute类中的一个属性// 调用MyRangeAttribute中的最大和最小值还有文字信息,用于绘制时候的显示MyRangeAttribute range = attribute as MyRangeAttribute;// 判断传进来的值类型if (property.propertyType == SerializedPropertyType.Float) {EditorGUI.Slider(position, property, range.min, range.max, range.label);} else if (property.propertyType == SerializedPropertyType.Integer) {EditorGUI.IntSlider(position, property, (int)range.min, (int)range.max, range.label);}}}

版权声明:本文为博主原创文章,未经博主允许不得转载。

诚实是人生绝妙的法宝。虽然对人诚实,

讲解如何在Unity的Inspector面板中用滑动条来控制变量的大小

相关文章:

你感兴趣的文章:

标签云: