mardi 24 janvier 2017

RandomRangeInt is not allowed to be called from a MonoBehavior constructor

I'm trying to genereate a random number by using th the UnityEngine.Random.Range(min, max) function, but I'm getting the following error:

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 'myClass' on game object 'GameObject'. See "Script Serialization" page in the Unity Manual for further details. UnityEngine.Random:Range(Int32, Int32)

And the following code (a simplified version from the one I'm using):

public class myClass : MonoBehavior {
    // Some instance variables
    List<Property> listA;
    int value;

   // Constructor
    public myClass(){
        init();
        search();
    }

    public void init(){
        // Some instructions
    }

    public void search(){
        int randomNumber = UnityEngine.Random.Range(0, 10); // Error!
    }
}

I've been searching on the Internet about this error, but I couldn't find any clear solution. For example:

http://ift.tt/2ko7X4B (but it isn't a static variable)

http://ift.tt/2jtjMTb (but I need the random number after calling Awake)




Aucun commentaire:

Enregistrer un commentaire