johnhattan icon

Simpler random class for Unity

johnhattan | PRO | 04/18/17 02:35:41 PM UTC | 0 ⭐ | 273 👁️ | Never ⏰ | []
C# |

2.4 KB

|

None

|

0 👍

/

0 👎

public static class Rnd // randoms should be simple, dagnabbit
{ // C# is pretty lazy about uints, so I'm just using ints
    private static readonly System.Random R = new System.Random();
 
    public static int Uint
    { // returns a random int between 0 and 2,147,483,647
        get
        {
            return R.Next();
        }
    }
    public static int UIntUpTo(int max)
    { // returns an integer between 0 and max
        return R.Next(max);
    }
    public static int UIntUpToInclusive(int max)
    { // returns an integer between 0 and max inclusive
        return R.Next(max + 1);
    }
    public static int UIntBetween(int min, int max)
    { // returns an integer between min and max
        return R.Next(min, max);
    }
    public static int UIntBetweenInclusive(int min, int max)
    { // returns an integer between min and max inclusive
        return R.Next(min, max + 1);
    }
 
    public static float Float
    { // traditional random number between 0 and 1 exclusive.
        get
        {
            return (float)R.NextDouble();
        }
    }
    public static float FloatUpTo(float max)
    { // returns a number between 0 inclusive and max exclusive
        return (float)(R.NextDouble() * max);
    }
    public static float FloatBetween(float min, float max)
    { // returns a number between min inclusive and max exclusive
        return (float)(R.NextDouble() * (max - min)) + min;
    }
 
    public static bool Bool
    { // returns true or false (50% chance of true)
        get
        {
            return (R.Next() & 0x01) == 0;
        }
    }
    public static bool BoolWeighted(float chance = 0.5f)
    { // returns true or false (chance% chance of true)
        return (R.NextDouble() < chance);
    }
 
    public static int Sign
    { // returns 1 or -1 (50% chance of 1)
        get
        {
            return ((R.Next() & 0x01) == 0) ? 1 : -1;
        }
    }
    public static int SignWeighted(float chance = 0.5f)
    { // returns 1 or -1 (chance% chance of 1)
        return (R.NextDouble() < chance) ? 1 : -1;
    }
 
    public static int Bit
    { // returns 1 or 0 (50% chance of 1)
        get
        {
            return R.Next() & 0x01;
        }
    }
    public static int BitWeighted(float chance = 0.5f)
    { // returns 1 or 0 (chance% chance of 1)
        return (R.NextDouble() < chance) ? 1 : 0;
    }
}

Comments