Thursday, September 5, 2013

Unity Helper Methods #3: GetRandomEnum

/// <summary>
/// Returns a random enum from the specified enum type
/// </summary>
/// <typeparam name="T">The enum</typeparam>
public static T GetRandomEnum<T>()
{
    Array values = Enum.GetValues(typeof(T));
    return  (T)values.GetValue(UnityEngine.Random.Range(0, values.Length));
}

Typical Usage

Fairly simple; returns a random enum value from an enum type.
enum EnemyModels
{
    Knight,
    FrailOldLady,
    Copernicus,
    BrianMay,
    MalboroGuy
}

void SpawnEnemy() 
{
    EnemyModels modelType = GetRandomEnum<EnemyModels>();
    // Now we have a random enemy model type.
}