Skip to content

Instantly share code, notes, and snippets.

@atil
Created January 29, 2017 14:43
Show Gist options
  • Save atil/30c6ab5ab23b56e042a967e586f11032 to your computer and use it in GitHub Desktop.
Save atil/30c6ab5ab23b56e042a967e586f11032 to your computer and use it in GitHub Desktop.
A number of extension / utility functions that come in handy for almost every project that I've worked on.
public static class Util
{
public static Vector3 Horizontal(this Vector3 v)
{
return Vector3.ProjectOnPlane(v, Vector3.up);
}
public static bool InBetween(this float val, float a, float b)
{
return (val < b && val > a) || (val < a && val > b);
}
public static T ToEnum<T>(this string value)
{
if (string.IsNullOrEmpty(value))
{
return default(T);
}
return (T)Enum.Parse(typeof(T), value, true);
}
public static FieldInfo[] GetFieldsMarkedWith<T>(object obj) where T : Attribute
{
return obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.GetCustomAttributes(typeof(T), true).Any()).ToArray();
}
public static Type[] GetChildrenTypesOf<T>()
{
return (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where typeof(T).IsAssignableFrom(assemblyType) && assemblyType != typeof(T)
select assemblyType).ToArray();
}
public static void SetAlpha(this Material m, float a)
{
var c = m.color;
c.a = a;
m.color = c;
}
public static void SetAlpha(this Image m, float a)
{
var c = m.color;
c.a = a;
m.color = c;
}
public static T Random<T>(this IList<T> list)
{
return list[UnityEngine.Random.Range(0, list.Count)];
}
public static void WaitForSeconds(float seconds, Action function)
{
Observable.Timer(TimeSpan.FromSeconds(seconds)).Subscribe(x => function());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment