Search code examples
c#classunity-game-enginerandomconstruct

Unity - Cannot generate random number within a class construct


I have been trying to create my own class using C# in Unity but I've come across a small issue. Within my PlayerClass construct I want to generate a string of six random numbers using Random.Range (0, 9) use as a reference number. Currently, the line of code I am using to do this, looks like this:

refNum = Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9);

I have created the variable refNum outside of the construct at the top of the class. Every time I run my game I get an error saying I cannot generate random numbers from within a class construct. Does anybody know a way around this?

Many Thanks,

Tommy


Solution

  • To have a string containing six random digits (0-9) you need first be sure of which Random class you want to use (the one from UnityEngine or from System). If you are using the one from UnityEngine, you should do something like this:

    string randomString = Random.Range(0, 9).ToString() + Random.Range(0, 9).ToString() + Random.Range(0, 9).ToString() + Random.Range(0, 9).ToString() + Random.Range(0, 9).ToString() + Random.Range(0, 9).ToString();
    

    Or perhaps a more elegant way to do it:

    string randomString = "";
        for (int i = 0; i < 6; i++)
            randomString += Random.Range(0, 9).ToString();