コガネブログ

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

【Unity】UnityException: XXXX is not allowed to be called from a MonoBehaviour constructor

概要

UnityException: XXXX is not allowed to be called 
from a MonoBehaviour constructor (or instance field initializer), 
call it in Awake or Start instead. Called from MonoBehaviour 'YYYY'.

上記のようなエラーが発生した場合は

using UnityEngine;

public class Example : MonoBehaviour
{
    // ここでエラー
    public Material m_material = Resources.Load<Material>( "" );
}

エラーが発生している箇所の初期化処理を

using UnityEngine;

public class Example : MonoBehaviour
{
    public Material m_material;

    private void Start()
    {
        m_material = Resources.Load<Material>( "" );
    }
}

Awake や Start に移動するとエラーが発生しなくなる