如何为你的美术妹子做Unity的小工具(三)

绘制脚本组件监视面板的内容

我们写了一个脚本Test

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Test : MonoBehaviour {
    public GameObject obj;
    public Color color;
    public Vector3 v3;
    public List<Transform> tran;
    public GameObject[] objarr;

    public TestClass test = new TestClass ();
}

public class TestClass{
    public int [] intArr;
    public List<string> list;
}

 

脚本中定义的public变量会显示在Inspector面板中

如果妹子们不喜欢英文 想看中文的  那该怎么办呢    今天,我们就来解决这个问题

我们写一个TestEditor 继承Editor  重写里面的OnInspectorGUi方法   必须放在Editor文件夹下

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(Test),true)]
public class TestEditor : Editor{ public override void OnInspectorGUI () {
     //base.OnInspectorGUI(); EditorGUILayout.IntField (
"", 0); } }

但是这样是没有直接的变化的   我们需要将 Test 和TestEditor 关联起来

[CustomEditor(typeof(Test),true)]

这句就是将此脚本与Test关联起来

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(Test),true)]
public class TestEditor : Editor{

    private Test mTest;

    public override void OnInspectorGUI ()
    {
        mTest = target as Test;            //关联的目标对象
        mTest.obj = EditorGUILayout.ObjectField ("对象",mTest.obj,typeof(GameObject)) as GameObject;         //目标对象的obj 
        mTest.color = EditorGUILayout.ColorField ("颜色", mTest.color);
        mTest.v3 = EditorGUILayout.Vector3Field ("三维向量", mTest.v3);
    }

   效果好像还不错的样子

这里搞定了前面三个  剩下的显示起来 方法有一点不一样

     //List的绘制   先获取序列化对象
        SerializedProperty proerty = serializedObject.FindProperty ("tran");
     //绘制序列化对象 EditorGUILayout.PropertyField (proerty,
new GUIContent ("游戏tran"), true);
     //保存序列化的操作
     serializedObject.ApplyModifiedProperties();

List在EditorGUILayout类下是没有方法直接进行加载的  但是有一个是用来加载序列化对象的  所以我们可以把List进行序列化  然后再将序列化后的对象进行加载

PropertyField 拥有多个重载  最多只有四个参数,第一个为序列化的对象    第二个是GUIContent 是个Label 并不是String  但是GUIContent是可以传string 所以我们new 一个GUIContent传入需要显示的文字,  第三个是否包含孩子如果为false的话  显示出来的是不包含size的

但是 这样对他操作是没有办法对操作进行保存的所以我们需要用serializedObject类中的 ApplyModifiedProperties()方法应用属性修改  这样在对它操作时就可以直接保存下来了

对象数组的初始化方法与List的相同  先获取序列化的对象  然后再进行绘制

     SerializedProperty proerty_objarr = serializedObject.FindProperty ("objarr");
        EditorGUILayout.PropertyField (proerty_objarr,new GUIContent ("游戏对象数组"), true);

在类对象显示时  需要对显示的类进行序列化

[System.Serializable]    //系统的序列化方法
public class TestClass {
    public int [] intArr;
    public List<string> list;
}    

然后再用相同的方法进行绘制就可以了

     SerializedProperty proerty_testclass = serializedObject.FindProperty ("test");      //获取序列化对象
        EditorGUILayout.PropertyField (proerty_testclass,new GUIContent ("类对象"), true);    //绘制

可以利用其它的GUILayout的绘制组件的方法进行组件的绘制  如绘制一个按钮

     if (GUILayout.Button ("测试按钮")) {
            Debug.Log("111");
        }

ok   这次就到这里吧  下次再见咯

posted @ 2015-12-23 09:58  我爱吃橙子  阅读(535)  评论(0编辑  收藏  举报