Unity3D 自定義編輯器介面(Inspector)
阿新 • • 發佈:2018-12-14
今天看一個指令碼,本想看看在 Inspector 介面的變數在腳本里的用途,然後查詢變數名的時候怎麼也找不到,自己也是驚訝。通過網上搜索才瞭解到原來 Inspector介面 是可以自己定義的。
當然自己定義,當然也需要寫一個指令碼來改的。可能是為了讓介面整潔的目的。
- 首先,在標頭檔案裡需要新增 using UnityEditor;
- 新建一個資料夾 命名為 Editor 因為我們需要 using unityEditor ,而是用這個的指令碼必須在名字為Editor 的資料夾下。在Editor 檔案下建立一個C#新指令碼 名字隨意,我取名為 EditTest
假設原來物體掛的指令碼名字是 Test
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test : MonoBehaviour { public int int_data; public float float_data; public Vector3 vector3_data; public bool bool_data; public Texture2D texture2d_data; public void PrintData() { Debug.Log("int_data=" + int_data); Debug.Log("float_data=" + float_data); Debug.Log("Vector3_data=" + vector3_data); Debug.Log("bool_data=" + bool_data); } }
修改介面指令碼為
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(Test))] //這裡Test是原來指令碼的名字 public class EditTest : Editor //繼承改為Editor { test test_scripts; //指令碼本體 SerializedObject serObj;//用來獲取各指令碼變數 SerializedProperty int_data; SerializedProperty float_data; SerializedProperty vector3_data; SerializedProperty bool_data; SerializedProperty texture2d_data; /// <summary> /// 初始化 Objcet物件,繫結各變數, 抓取腳本里面的屬性 /// </summary> private void OnEnable() { test_scripts= (test)target; serObj = new SerializedObject(target); int_data = serObj.FindProperty("int_data"); float_data = serObj.FindProperty("float_data"); vector3_data = serObj.FindProperty("vector3_data"); bool_data = serObj.FindProperty("bool_data"); texture2d_data = serObj.FindProperty("texture2d_data"); } /// <summary> /// 顯示 /// </summary> public override void OnInspectorGUI() //更新指令碼的資訊 { serObj.Update(); EditorGUILayout.LabelField("以下是各資料的設定", EditorStyles.miniLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(int_data, new GUIContent("int_data")); EditorGUILayout.Slider(float_data, 0.0f, 50.0f, new GUIContent("float_data")); //滑動條 EditorGUILayout.PropertyField(vector3_data, new GUIContent("vector3_data")); EditorGUILayout.PropertyField(bool_data, new GUIContent("bool_data")); EditorGUILayout.PropertyField(texture2d_data, new GUIContent("texture2d_data")); EditorGUILayout.EndFadeGroup(); if (GUILayout.Button("輸出資訊")) { test_scripts.PrintData(); } serObj.ApplyModifiedProperties(); //最後,通過此應用修改屬性效果 } }