溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用反射來實現(xiàn)將自定義類型顯示在Unity的Inspector上

發(fā)布時間:2021-11-15 16:20:37 來源:億速云 閱讀:304 作者:柒染 欄目:大數(shù)據(jù)

這期內(nèi)容當中小編將會給大家?guī)碛嘘P(guān)如何用反射來實現(xiàn)將自定義類型顯示在Unity的Inspector上,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

最近準備在Unity調(diào)試移植的FixedB2CSharp,整個庫是基于定點數(shù)的,所以首先需要將定點數(shù)序列化顯示在Inspector上,沒想到一腳就踩進了坑里。

一般來說,要實現(xiàn)我這個需求,用PropertyDrawer就好了,照著Unity的API手冊改一改也就能用了。但是,我這個定點數(shù)類型還是有些不一樣的,以下是關(guān)鍵部分代碼的節(jié)選:

[Serializable]
public struct Fix64{
    public long RawValue { get; }

    //...

    public static explicit operator float(Fix64 value){
        //...
    }
}

我可以說想盡辦法也沒能從SerializedProperty這個類型中直接獲取到Fix64類型的目標值,所以我左思右想,既然是編輯器腳本,直接上反射試試?

說干就干,先看看API手冊,怎么才能拿到目標值的引用?一般來說,這種引用都是object,所以先去看看SerializedProperty里沒有object類型的成員,確認過眼神,沒有。

思考一下,SerializedProperty是什么?他是想要顯示在Inspector上的一個屬性,和MonoBehaviour,ScriptableObject等類型不同,他是像Vector2一樣的非UnityEngine.Object類型,所以我們拿到他所在類的實例,再通過反射去查找這個屬性,不就獲取到了他的值了嗎?

所以我們首先通過property.serializedObject.targetObject拿到了實際上我們在Inspector上顯示的UnityEngine.Object類型,然后又有了property.propertyPath提供的目錄,我們很輕松的就通過反射拿到了他的父級類型的實例,為了測試,我這里寫了一個MonoBehaviour腳本:

public class EditorGUITest: MonoBehaviour {
   public FixedDt typeafae21;

   public float xf = 1616;
}

[Serializable]
public class FixedDt {
   public Fix64 afafafafa;
   public Fix64 f2wfsfaeaf;
}

最終我們拿到了EditorGUITest的成員typeafae21,類型為FixedDt的實例。

最后我們通過property.name這個屬性,反射獲得想要的值。

思路有了代碼就很簡單,這里直接上完整代碼:

[CustomPropertyDrawer(typeof(Fix64))]
public class Fix64Drawer : PropertyDrawer {
   // Draw the property inside the given rect
   public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
      using (new EditorGUI.PropertyScope(position, label, property)) {
         var parent = GetParentObjectOfProperty(property.propertyPath, property.serializedObject.targetObject);

         var type = parent.GetType();
         var pi = type.GetField(property.name);
         var o = pi.GetValue(parent);
         var value = (Fix64) o;

         value = EditorGUI.FloatField(position, label, (float) value);

         pi.SetValue(parent,value);
      }
   }

   private object GetParentObjectOfProperty(string path, object obj) {
      while (true) {
         var fields = path.Split('.');

         if (fields.Length == 1) {
            return obj;
         }

         var fi = obj.GetType()
                  .GetField(fields[0], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

         obj = fi.GetValue(obj);

         path = string.Join(".", fields, 1, fields.Length - 1);
      }
   }
}

上述就是小編為大家分享的如何用反射來實現(xiàn)將自定義類型顯示在Unity的Inspector上了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI