viva viva - 4 months ago 14
C# Question

How to pass same number into many functions

I have a script which generates random number, I also have many other scripts which have to receive that random number from first script.

That is what I tried, but it doesn't work. Always gives 0 as result.

int xNum;

int generateNum()
return Random.Range(10, 100);

void Start()
xNum = generateNum();

public int Getnumber()
return xNum;

And then I call Getnumber() method in another script, but as I said it returns always 0. Any suggestions what I'm doing wrong?

P.S random number have to be the same in all other scripts

Answer Source

If you want to generate this random number only once or "on demand" then I would suggest you doing something like this:

int? _generatedRandom;
public int GeneratedRandom
    get { 
        if ( !_generatedRandom.HasValue )

        return _generatedRandom.Value;

void GenerateRandom()
    _generatedRandom = Random.Next(10, 100);

Then from your other scripts you can just call :

int randomNumber = MeRandomNumberClass.GeneratedRandom;