コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】UnityException: LoadSerializedFileAndForget is not allowed to be called from a ScriptableObject constructor (or instance field initializer), call it in OnEnable instead. Called from ScriptableObject 'XXXX'.

概要

[InitializeOnLoad]
internal static class Example
{
    static Example()
    {
        Debug.Log( ExampleSetting.instance );
    }
}

InitializeOnLoad のタイミングで ScriptableSingleton にアクセスしたら

UnityException: LoadSerializedFileAndForget is not allowed to be called from a ScriptableObject constructor (or instance field initializer), call it in OnEnable instead. Called from ScriptableObject 'XXXX'.
See "Script Serialization" page in the Unity Manual for further details.

上記の例外が発生した

[InitializeOnLoad]
internal static class Example
{
    static Example()
    {
        EditorApplication.delayCall += () =>
        {
            Debug.Log( ExampleSetting.instance );
        };
    }
}

1 フレーム遅らせたら例外が発生しなくなった