Unity自定義Inspectors

在Unity中,有時候需要自定義腳本在inspector中的顯示,具體操作如下:
1.首先我們要在Editor文件夾下建立一個腳本,範例如下:

using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor (typeof (MyPlayer))]      
[CanEditMultipleObjects]
public class MyPlayerEditor : Editor {

    SerializedProperty damageProp;
    SerializedProperty armorProp;
    SerializedProperty gunProp;


    void OnEnable () {
        // Setup the SerializedProperties
        damageProp = serializedObject.FindProperty ("damage");
        armorProp = serializedObject.FindProperty ("armor");
        gunProp = serializedObject.FindProperty ("gun");
    }

    public override void OnInspectorGUI() {
        // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
        serializedObject.Update ();
        // Show the custom GUI controls
        EditorGUILayout.IntSlider (damageProp, 0, 100, new GUIContent ("Damage"));
        // Only show the damage progress bar if all the objects have the same damage value:
        if (!damageProp.hasMultipleDifferentValues)
            ProgressBar (damageProp.intValue / 100.0f, "Damage");
        EditorGUILayout.IntSlider (armorProp, 0, 100, new GUIContent ("Armor"));
        // Only show the armor progress bar if all the objects have the same armor value:
        if (!armorProp.hasMultipleDifferentValues)
            ProgressBar (armorProp.intValue / 100.0f, "Armor");
        EditorGUILayout.PropertyField (gunProp, new GUIContent ("Gun Object"));
        // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI.
        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 ();
    }
}

2.下面是我們要顯示在Inpsector中的簡單腳本:

public int damage;
    public GameObject gun;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
}

以下是最終效果圖:
這裏寫圖片描述

發佈了36 篇原創文章 · 獲贊 29 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章