Unity自定义Inspectors

好久不见. 提交于 2019-11-26 02:10:59

在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 () {

    }
}

以下是最终效果图:
这里写图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!