EpicRandom.cs for our #UnityTips Friends

So I've been tweeting out helpful tips to the Unity developer community with the tag #UnityTips to share useful tidbits I've learned over the past few months dabbling with C# and Unity.

Today we got a retweet from Unity @Unity3D. Several people commented asking what is the EpicRandom code class that my example referred to.

Figured I'd share the class we're using for anyone interested. EpicRandom is just a simple collection of a few C# randomization helper functions we've gathered for BioBeasts:

I'm sure we'll keep adding to it and expanding the class as the project and our needs change. If you have any suggestions please post below!

using System;  
using System.Collections.Generic;

public static class EpicRandom  
{
    public static int Range(int min, int max)
    {
        return UnityEngine.Random.Range(min, max + 1);
    }

    public static float Range(float min, float max)
    {
        return UnityEngine.Random.Range(min, max);
    }

    // Be careful of calling this too frequently as it allocs an array each time
    public static T GetRandomEnum<T>()
    {
        return GetRandomEnum<T>(0, Enum.GetNames(typeof(T)).Length - 1);
    }

    public static T GetRandomEnum<T>(int startIndex, int endIndex)
    {
        System.Array array = System.Enum.GetValues(typeof(T));

        startIndex = EpicUtils.Clamp(startIndex, 0, endIndex);
        endIndex = EpicUtils.Clamp(endIndex, startIndex, array.Length - 1);

        T value = (T)array.GetValue(Range(startIndex, endIndex));
        return value;
    }


    public static void ShuffleList<T>(this IList<T> list)
    {
        ShuffleList<T>(list, 0, list.Count - 1);
    }

    public static void ShuffleList<T>(this IList<T> list, int startIndex, int endIndex)
    {
        startIndex = EpicUtils.Clamp(startIndex, 0, endIndex);
        endIndex = EpicUtils.Clamp(endIndex, startIndex, list.Count - 1);

        for (int i = startIndex; i < endIndex; i++)
        {
            int j = Range(i, endIndex);
            T swap = list[j];
            list[j] = list[i];
            list[i] = swap;
        }
    }

    public static T GetRandomElementOfList<T>(List<T> list)
    {
        return list[Range(0, list.Count - 1)];
    }
}
Artix Entertainment
Artix Entertainment
Copyright © 2017 Artix Entertainment, LLC | Privacy Policy | Terms & Conditions