Unity中的GUIStyle错误:SerializedObject of SerializedProperty has been Disposed.

笔者在GUI练习中发现此问题。

如果读者也遇到这个问题,很可能与 Unity 或相关库的版本不兼容或其他问题有关。

笔者的示例代码1:

public class L1_GUI : MonoBehaviour
{
    public GUIStyle Mystyle = new GUIStyle();

    private void OnGUI()
    {
        Mystyle.fontSize = 12;
        
        // 显示文字
        GUI.Label(new Rect(0, 0, 20, 20), "This.", Mystyle);
    }
}

示例代码2:

public class L1_GUI : MonoBehaviour
{
    public GUIStyle Mystyle;
}

以上代码1和代码2,均在 Unity编辑器 2022.3.0f1c1 版本上循环打印

        NullReferenceException: SerializedObject of SerializedProperty has been Disposed. 错误。

        无论是否在OnGUI函数中使用这个参数Mystyle,都会产生NullReferenceException错误。并且右侧的GUIStyle面板是残缺的(无法实时刷新此GUIStyle的各种参数)

该错误的解释大致是:

        NullReferenceException 通常表示对象引用为空。在这种情况下,SerializedObject 对象已经 Disposed,因此在使用它时会导致 NullReferenceException 异常。通常情况下,SerializedObject 对象在使用完毕后应该被显式地 Dispose,在这个情景下应该是被异常地提前Dispose了。

一番折腾后,切换至 Unity编辑器 2021.3.19f1c1 版本,错误不再产生。

执行正常的打印信息:


 

猜你喜欢

转载自blog.csdn.net/qingxiu3733/article/details/131750782