Created
November 2, 2015 04:18
-
-
Save grimmdev/43aef4716b1b9e5e7edd to your computer and use it in GitHub Desktop.
List Extensions for Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public static class ListExtensions | |
{ | |
private static System.Random s_rand = new System.Random(); | |
public static T RandomElement<T>(this List<T> source) | |
{ | |
if (source.Count == 0) | |
{ | |
return default(T); | |
} | |
return source[ListExtensions.s_rand.Next(source.Count)]; | |
} | |
public static float GetFloat(this List<object> list, int index, float defaultValue = 0f) | |
{ | |
float result; | |
try | |
{ | |
result = ((index >= list.Count) ? defaultValue : ((float)Convert.ToDouble(list[index]))); | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogWarning(string.Format("Fail to convert (key<{0}>, value<{1}>) to {2}. Error: {3}", new object[] | |
{ | |
index, | |
list[index], | |
"float", | |
ex.Message | |
})); | |
result = defaultValue; | |
} | |
return result; | |
} | |
public static int GetInt(this List<object> list, int index, int defaultValue = 0) | |
{ | |
int result; | |
try | |
{ | |
result = ((index >= list.Count) ? defaultValue : Convert.ToInt32(list[index])); | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogWarning(string.Format("Fail to convert (key<{0}>, value<{1}>) to {2}. Error: {3}", new object[] | |
{ | |
index, | |
list[index], | |
"int", | |
ex.Message | |
})); | |
result = defaultValue; | |
} | |
return result; | |
} | |
public static T GetEnum<T>(this List<object> list, int index, T defaultValue) | |
{ | |
string text = (index >= list.Count) ? null : (list[index] as string); | |
T result; | |
try | |
{ | |
if (Enum.IsDefined(typeof(T), text)) | |
{ | |
result = (string.IsNullOrEmpty(text) ? defaultValue : ((T)((object)Enum.Parse(typeof(T), text)))); | |
} | |
else | |
{ | |
Debug.LogWarning(string.Format("Fail to convert (key<{0}>, value<{1}>) to {2}<{3}>. Error: {4}", new object[] | |
{ | |
index, | |
text, | |
"enum", | |
typeof(T), | |
"Not an underlying value of this enumeration" | |
})); | |
result = defaultValue; | |
} | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogWarning(string.Format("Fail to convert (key<{0}>, value<{1}>) to {2}<{3}>. Error: {4}", new object[] | |
{ | |
index, | |
text, | |
"enum", | |
typeof(T), | |
ex.Message | |
})); | |
result = defaultValue; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment