unity, SerializedObject.FindProperty不要寫在Editor的OnEnable裏,要寫在OnInspectorGUI裏

若是像下面這樣寫:ide

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine.Assertions.Must;
[CustomEditor(typeof(xxxControl))]
public class xxxControlEditor : Editor
{
    SerializedProperty m_a;
    void OnEnable(){ui

    m_a=serializedObject.FindProperty ("m_a");
    }
    public override void OnInspectorGUI()
    {get

     /////DrawDefaultInspector();it

        serializedObject.Update ();
        EditorGUILayout.PropertyField(m_a,true);
        serializedObject.ApplyModifiedProperties ();
    }io

}class

則在其它Editor或EditorWindow腳本的中調用date

    Editor _editor=Editor.CreateEditor(xxxObj.GetComponent<xxxControl>()); call

就會報以下錯誤:腳本

NullReferenceException: (null)
UnityEditor.SerializedObject..ctor (UnityEngine.Object[] objs) (at C:/buildslave/unity/build/artifacts/generated/common/editor/SerializedPropertyBindings.gen.cs:72)
UnityEditor.Editor.GetSerializedObjectInternal () (at C:/buildslave/unity/build/artifacts/generated/common/editor/EditorBindings.gen.cs:151)
UnityEditor.Editor.get_serializedObject () (at C:/buildslave/unity/build/artifacts/generated/common/editor/EditorBindings.gen.cs:144)
xxxControlEditor.OnEnable () (at Assets/??/Editor/xxxControlEditor.cs:??)di

若是將SerializedObject.FindProperty從OnEnable中改到OnInspectorGUI中,即:

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine.Assertions.Must;
[CustomEditor(typeof(xxxControl))]
public class xxxControlEditor : Editor
{
    SerializedProperty m_a;
    void OnEnable(){
    }
    public override void OnInspectorGUI()
    {

     /////DrawDefaultInspector();

    m_a=serializedObject.FindProperty ("m_a");//serializedObject.FindProperty should be called in OnInspectorGUI() instead of OnEnable()

        serializedObject.Update ();
        EditorGUILayout.PropertyField(m_a,true);
        serializedObject.ApplyModifiedProperties ();
    }

}

則不會出現上述錯誤。

相關文章
相關標籤/搜索