Unity中允許用戶對腳本的屬性進行自定義編輯,被編輯的類需要用[Serializable]修飾凯力,編輯器類繼承Editor并重寫OnInspectorGUI()方法旅挤,具體的排版在這個方法中繪制。
常用的基本方法:
//獲取屬性 serializedObject.FindProperty("age");
//顯示屬性,類型會自動獲取 EditorGUILayout.PropertyField(ageProp, new GUIContent("age"));
//應(yīng)用修改項 serializedObject.ApplyModifiedProperties();
//對象需要一直更新 serializedObject.Update();
下面放代碼笼吟,將RoleController.cs掛在物體上库物,將EditorInspector.cs放在工程的Editor目錄。
using UnityEngine;
using System;
using System.Collections;
[Serializable]
public class RoleController :MonoBehaviour
{
public string roleName = "asadasd";
public int age;
public float range;
public float jumpHight;
public Texture2D pic;
public string picName;
public moveType ac;
public bool isBoy;
}
public enum moveType
{
jump,
move,
attack
}
Editor腳本
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(RoleController))]
[CanEditMultipleObjects]
public class EditorInspector : Editor
{
private RoleController role;
bool toggle;
SerializedProperty ageProp;
SerializedProperty nameProp;
SerializedProperty picProp;
SerializedProperty rangeProp;
SerializedProperty boolProp;
SerializedProperty enumProp;
void OnEnable()
{
// Setup the SerializedProperties.
ageProp = serializedObject.FindProperty("age");
nameProp = serializedObject.FindProperty("roleName");
picProp = serializedObject.FindProperty("pic");
rangeProp = serializedObject.FindProperty("range");
boolProp = serializedObject.FindProperty("isBoy");
enumProp = serializedObject.FindProperty("ac");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
role = target as RoleController;
GUILayout.Space(6f);
//role.age = EditorGUILayout.IntSlider("Age", role.age, 0, 100);
//role.roleName = EditorGUILayout.TextField("角色名字", role.roleName);
EditorGUILayout.PropertyField(ageProp, new GUIContent("age"));
EditorGUILayout.PropertyField(nameProp, new GUIContent("name"));
EditorGUILayout.PropertyField(boolProp, new GUIContent("isBoy"));
EditorGUILayout.PropertyField(enumProp, new GUIContent("enum"));
if (EditorGUILayout.Foldout(toggle, "折疊"))
{
EditorGUILayout.PropertyField(picProp, new GUIContent("pic"));
}
EditorGUILayout.Slider(rangeProp, 0, 100, new GUIContent("range"));
ProgressBar(rangeProp.floatValue/100, "range");
serializedObject.ApplyModifiedProperties();
}
// Custom GUILayout progress bar.
void ProgressBar(float value, string label)
{
// Get a rect for the progress bar using the same margins as a textfield:
Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField");
EditorGUI.ProgressBar(rect, value, label);
EditorGUILayout.Space();
}
}
現(xiàn)在大家可以根據(jù)自己的需求進行拓展了贷帮。