這期內容當中小編將會給大家帶來有關如何用反射來實現將自定義類型顯示在Unity的Inspector上,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
最近準備在Unity調試移植的FixedB2CSharp,整個庫是基于定點數的,所以首先需要將定點數序列化顯示在Inspector上,沒想到一腳就踩進了坑里。
一般來說,要實現我這個需求,用PropertyDrawer就好了,照著Unity的API手冊改一改也就能用了。但是,我這個定點數類型還是有些不一樣的,以下是關鍵部分代碼的節選:
[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);
}
}
}上述就是小編為大家分享的如何用反射來實現將自定義類型顯示在Unity的Inspector上了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。