unity, SerializedObject.FindProperty不要写在Editor的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(){

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

     /////DrawDefaultInspector();

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

}

则在其它Editor或EditorWindow脚本的中调用

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

就会报如下错误:

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:??)

如果将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 ();
    }

}

则不会出现上述错误。

posted on 2016-05-12 16:29  wantnon  阅读(9063)  评论(0编辑  收藏  举报

导航