Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Numbers in Unity3D?

What I found was how to create random numbers. Great. This solution, however, was not working in other functions. To create a random number, I used

Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 4); 

inside of a function called enemyWalk(){};

However, this caused an error:

Type 'UnityEngine.Random' does not contain a definition for 'Next' and no extension method 'Next' of type 'UnityEngine.Random' could be found (are you missing a using directive or an assembly reference?)

This error does not appear when I take the random integer generator out of the function. Any solutions to fix this problem?

I'm hoping to use this code to make my enemy wander around when not doing anything by randomly choosing an integer that decides which direction he walks (up, left, right, or down), then using a random double generator to determine the distance it walks. However I need a random number generated whenever enemyWalk(){}; is called.

like image 234
Jeff Avatar asked Jan 27 '15 01:01

Jeff


People also ask

How do I get a list of random elements in unity?

There's a simple, single-line method for getting a random number within a range: int randomNumber = Random. Range(0, 2); This little code will instantly provide you with either a '0' or a '1' as a result, and it will place the result in the randomNumber variable for later use.


2 Answers

In Unity C# the method is as follows

Random.Range(minVal, maxVal);

See Unity Documentation - Random

The method will accept either integer or float arguments. If using ints minVal is inclusive and maxVal is exclusive of the returned random value. In your case it would be:

Random.Range(1,4);

Instead of Next(1,4).

If using floats, for example

Random.Range(1.0F, 3.5F);

The return value is also a float, minVal and maxVal are inclusive in this case.

like image 66
Michael Avatar answered Oct 21 '22 13:10

Michael


The simple solution would be to just use .NET's Random class, which happens to be in the System namespace:

using System;

...

//Or System.Random without the using
Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 5);

If you want to use Unity's, call Range instead of Next:

int directionChoice = randomDirection.Range(1, 5);

Note that "max" is exclusive in both cases, so you should use 5 to return values between 1 and 4 (including 4)

To get random float:

Random.NextDouble(); //careful, this is between 0 and 1, you have to scale it
//Also, this one is exclusive on the upper bound (1)

Random.Range(1f, 4f); //max is inclusive now
like image 7
BradleyDotNET Avatar answered Oct 21 '22 13:10

BradleyDotNET