コガネブログ

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

【Unity】RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'XXXX' on game object 'YYYY'.

概要

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

上記のエラーは、次のようなコードを記述した場合に発生します

using UnityEngine;

public class Example : MonoBehaviour
{
    private int value = Random.Range( -1, 1 );
}

回避方法としては、Random クラスを使用するコードを
Awake か Start に移動します

using UnityEngine;

public class Example : MonoBehaviour
{
    private int value;
    
    private void Awake()
    {
        value = Random.Range( -1, 1 );
    }
}