UnityEditor扩展 - Vuforia license like文本输入框

接下来会用一系列实例文章,逐个功能讲解,希望能分享UnityEditor的奥义。

本文是做一个Vuforia License一样的输入框。如图:


(图1)

首先创建1对脚本(之后关于Editor的编辑,都将以一个XXX.cs和一个XXXEditor.cs成对出现)。

(图2)

License.cs 

很简单,定义一个public的string类型,以便让Editor调用。[HideInInspector]属性,作用顾名思义可以在Inspector中隐藏。

由于Editor会为我们重新排版并产生一个text field,原来的可以不作显示。(当然你也可以显示出来看一下有什么效果)

using UnityEngine;

public class License : MonoBehaviour
{
    [HideInInspector]
    public string mLicenseKey;

	void Start ()
    {
		
	}
}

LicenseEditor.cs 

首先是继承Editor。并在类上方定义属性,指定是对License类的编辑[CustomEditor(typeof(License), true)]。

Editor编辑中常用的类型有SerializedProperty序列化属性,SerializedObject序列化对象。分别用来指定License中的string\int\float\bool这些数据类型和指定gameObject对象。

OnEnable中,通过serializedObject.FindProperty(" ")对两个脚本中的数据进行连接。this的量指Editor中定义的,base指License.cs中定义的。

OnInspectorGUI是一个类似Update的生命周期,会在非运行时实时刷新。

由于重新排版了,默认在License里面即使public修饰也会被隐藏。DrawDefaultInspector() 方法可以将License中的公共变量在inspector中显示出来。

EditorGUILayout.PropertyField() 就是绘制新的文本框,可以自定义框的大小。

EditorStyles.textField.wordWrap = true; 是让新的文本框内的文字自动换行,设为false则只在一行内显示。

最后所有的变更,要使用base.serializedObject.ApplyModifiedProperties()来应用,否则新的文本框是不起作用的。

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(License), true)]
public class LicenseEditor : Editor
{
    private SerializedProperty mLicenseKey;
    private SerializedObject mLicense;

    //Method
    void OnEnable()
    {
        this.mLicenseKey = base.serializedObject.FindProperty("mLicenseKey");
    }

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        EditorGUILayout.PropertyField(this.mLicenseKey, new GUIContent("App License Key"), new GUILayoutOption[] { GUILayout.MinHeight(40f), GUILayout.MaxHeight(100f) });
        this.mLicenseKey.stringValue = this.mLicenseKey.stringValue.Replace(" ", "").Replace("\n", "").Replace("\r", "");
        EditorStyles.textField.wordWrap = true; // 自动换行

        base.serializedObject.ApplyModifiedProperties();
    }
}

终了,看一下我们做的效果。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值