Question

I can generate a random number between 1 and 3 fairly easy.

float x = Random.Range(1, 3);

But I am trying to generate a random number between 1 and 3, including 1 decimal place. i.e 1.0, 1.1, 1.2 - 2.8, 2.9, 3.0 Any help appreciate. I am finding no easy function to do this.

Note - I am using .cs script in Unity

Était-ce utile?

La solution

You can multiply the result like this:

float result = rnd.Next(10, 31) * .1f;

This will result in a range from 1.0 to 3.0, stepping by .1.

Autres conseils

This seems solid.

class Program
{
    static void Main(string[] args)
    {
        float fMyNumber = 0;

        Random rnd = new Random(Guid.NewGuid().GetHashCode());
        for (int j = 0; j < 20; j++) {
            fMyNumber = rnd.Next(1, 4);
            fMyNumber += ((float)rnd.Next(10)) / 10;
            Console.WriteLine(fMyNumber.ToString("0.0"));
        }
        Console.ReadLine();
    }
}

Simply add decimal numbers to your original code:

Random.Range(1.0, 3.0);

Make sure the variable you are applying the Random.Range() method to is a float and not an int. Also where using the method make sure you put f after each float e.g. Random.Range(1.0f, 3.0f).

Random.Range is maximally exclusive so you may want to use 3.1f to include up to 3.0f.

I know this thread is old just thought I'd try and help for anyone else looking at it.

For those using Unity, use System.Random.

For instance:

System.Random rnd = new System.Random();

Unity has it's own random object that's getting in the way.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top