赞
踩
在Unity编辑器中,所有对象(UnityEngine.Object)都会被转换为SerializedObject并进行处理。当我们在Inspector中编辑组件的值时,其实不是在编辑Component组件的实例,而是在编辑SerializedObject的实例
文件中的资源(.prefab、,scene)实际上是对象序列化后的格式,.meta文件是保存导入设置,在导入资源时,会从资源和.meta文件中生成SerializedObject(如果没有.meta文件,则默认自动生成一个),并转换为UnityEngine.Object
——获取某个对象的可序列化字段值
- using UnityEditor;
- using UnityEngine;
-
- public class Test : MonoBehaviour
- {
- [SerializeField]
- int m_v1 = 5;
-
- private void Start()
- {
- SerializedObject serializedObject = new SerializedObject(this);
- SerializedProperty serializedProperty = serializedObject.FindProperty("m_v1");
- Debug.Log(serializedProperty.intValue);
- }
- }
——获取序列化对象中所有字段
Next:所有可序列化的字段(包括面板上使用HideInInspector特性的字段)
NextVisible:所有可序列化的可见的字段(不包括面板上使用HideInInspector特性的字段)
参数代表是否遍历子字段中的属性
- using UnityEditor;
- using UnityEngine;
-
- public class Test: MonoBehaviour
- {
- [SerializeField]
- [HideInInspector]
- int m_v1 = 2;
- int m_v2 = 5;
-
- private void Start()
- {
- SerializedObject serializedObject = new SerializedObject(this);
- SerializedProperty serializedProperty = serializedObject.GetIterator();
- while (serializedProperty.NextVisible(true))
- {
- Debug.Log(serializedProperty.propertyPath);
- }
- }
- }

——ApplyModifiedProperties和ApplyModifiedPropertiesWithoutUndo
应用属性的修改
——Update
更新到属性的最新值
- using UnityEditor;
- using UnityEngine;
-
- public class Test : MonoBehaviour
- {
- public int a;
- [SerializeField]
- int b;
- [SerializeField]
- int[] array;
-
- private void Start()
- {
- SerializedObject so = new SerializedObject(this);
- so.Update();
-
- SerializedProperty a = so.FindProperty("a");
-
- a.intValue = 2;
-
- var array = so.FindProperty("array");
- array.InsertArrayElementAtIndex(0);
- SerializedProperty arrayElement = array.GetArrayElementAtIndex(0);
- arrayElement.intValue = 2;
-
- so.ApplyModifiedProperties();
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。