0

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

Programmer
  • 121,791
  • 22
  • 236
  • 328
TommyE
  • 338
  • 4
  • 7
  • 18

1 Answers1

1

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();
grafo
  • 154
  • 2
  • 10
  • I have made a separate function within my PlayerClass which holds your second way of generating a random number. It works but I cannot call it through my constructor. Is there anyway that I can call this function each time I create a new variable of type PlayerClass from any other script? – TommyE Jul 27 '17 at 17:35
  • I have reproduced what you described without any errors. Have you ensured that you are declaring `using UnityEngine;` in the file that you are writing your `PlayerClass`? – grafo Jul 27 '17 at 18:36
  • Yes I am definitely using UnityEngine – TommyE Jul 27 '17 at 18:38
  • Could you include the error log in your question? It could be helpful – grafo Jul 27 '17 at 19:14
  • 1
    Never mind. I used this method then just called the function from the script where I was creating the new variable. Thank you! – TommyE Jul 28 '17 at 19:01