-
-
Save kirillrybin/76dae57c5795e088d9f1 to your computer and use it in GitHub Desktop.
ExtensionMethods for Unity3D/C#
This file contains 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 System.Text.RegularExpressions; | |
using UnityEngine; | |
public static class ExtensionMethods | |
{ | |
public static int Round(this float value) | |
{ | |
var decimalpoints = Math.Abs(value - Math.Floor(value)); | |
return decimalpoints < 0.5 | |
? Mathf.FloorToInt(value) | |
: Mathf.CeilToInt(value); | |
} | |
public static bool IsValidEmailAddress(this string s) | |
{ | |
var regex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"); | |
return regex.IsMatch(s); | |
} | |
public static bool IsValidPhone(this string phone) | |
{ | |
var regex = new Regex(@"^\+?7\d{10}(?:#\d+)?$"); | |
return regex.IsMatch(phone); | |
} | |
#region Arrays | |
public static void Shuffle<T>(this T[] obj) | |
{ | |
for (var i = 0; i < obj.Length; i++) | |
{ | |
var temp = obj[i]; | |
var obj_index = UnityEngine.Random.Range(0, obj.Length); | |
obj[i] = obj[obj_index]; | |
obj[obj_index] = temp; | |
} | |
} | |
public static T GetRandomItem<T>(this T[] array) | |
{ | |
return array[UnityEngine.Random.Range(0, array.Length)]; | |
} | |
#endregion | |
#region Values | |
public static float Remap(this float value, float from1, float to1, float from2, float to2) | |
{ | |
return (value - from1) / (to1 - from1) * (to2 - from2) + from2; | |
} | |
public static float ToFloat(this string value) | |
{ | |
float floatValue; | |
float.TryParse(value.Replace(",", "."), out floatValue); | |
return floatValue; | |
} | |
public static int ToInt(this string value) | |
{ | |
int intValue; | |
int.TryParse(value, out intValue); | |
return intValue; | |
} | |
public static double ToDouble(this string value) | |
{ | |
double doubleValue; | |
double.TryParse(value.Replace(",", "."), out doubleValue); | |
return doubleValue; | |
} | |
public static int[] ToDigitArr(this int n) | |
{ | |
if (n == 0) return new[] { 0 }; | |
var digits = new List<int>(); | |
for (; n != 0; n /= 10) | |
digits.Add(n % 10); | |
var arr = digits.ToArray(); | |
Array.Reverse(arr); | |
return arr; | |
} | |
#endregion | |
#region Color | |
public static Color HexToColor(this string hex) | |
{ | |
byte r = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); | |
byte g = byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); | |
byte b = byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); | |
return new Color32(r, g, b, 255); | |
} | |
public static string ColorToHex(this Color32 color) | |
{ | |
string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2"); | |
return hex; | |
} | |
#endregion | |
#region GameObject | |
static public T AddSafeComponent<T>(this GameObject go) where T : Component | |
{ | |
T comp = go.GetComponent<T>(); | |
if (comp == null) | |
{ | |
comp = go.AddComponent<T>(); | |
} | |
return comp; | |
} | |
/// <summary> | |
/// Create nested GameObject with identity parameters | |
/// </summary> | |
/// <param name="parent">Parent GameObject</param> | |
/// <param name="name">Name of nested GameObject</param> | |
/// <returns></returns> | |
public static GameObject CreateNestedGameObject(this GameObject parent, string name) | |
{ | |
var nestedGo = new GameObject(name); | |
nestedGo.transform.parent = parent.transform; | |
nestedGo.transform.localScale = Vector3.one; | |
nestedGo.transform.localRotation = Quaternion.identity; | |
nestedGo.transform.localPosition = Vector3.zero; | |
return nestedGo; | |
} | |
public static void DestroyAllChildren(this Transform parent) | |
{ | |
var children = new List<GameObject>(); | |
foreach (Transform child in parent) children.Add(child.gameObject); | |
children.ForEach(child => GameObject.Destroy(child)); | |
} | |
#endregion | |
#region String | |
/// <summary> | |
/// Возвращает слово в нужном падеже | |
/// </summary> | |
/// <param name="num">Число, требующее падежа</param> | |
/// <param name="one">1 - минута</param> | |
/// <param name="little">2 - минуты</param> | |
/// <param name="many">5 - минут</param> | |
/// <returns></returns> | |
public static string StringCaseByNum(this int num, string one, string little, string many) | |
{ | |
if (num % 100 > 10 && num % 100 < 15) | |
return many; | |
if (num % 10 == 1) | |
return one; | |
if (num % 10 > 1 && num % 10 < 5) | |
return little; | |
return many; | |
} | |
/// <summary> | |
/// Возвращает слово в нужном падеже | |
/// </summary> | |
/// <param name="input">Дата, например "01.01.2016"</param> | |
/// <param name="inputFormat">Формат переменной input</param> | |
/// <returns>Объект даты сконвертироный из строки</returns> | |
public static DateTime toDateTime(this string input, string inputFormat = "dd.MM.yyyy") | |
{ | |
return DateTime.ParseExact(input, inputFormat, | |
System.Globalization.CultureInfo.InvariantCulture); | |
} | |
#endregion | |
#region Time | |
public static DateTime ConvertFromUnixTimestamp(this double timestamp) | |
{ | |
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); | |
return origin.AddSeconds(timestamp); | |
} | |
public static double ConvertToUnixTimestamp(this DateTime date) | |
{ | |
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); | |
TimeSpan diff = date - origin; | |
return Math.Floor(diff.TotalSeconds); | |
} | |
#endregion | |
#region Mesh | |
/// <summary> | |
/// Create mesh from vertices | |
/// </summary> | |
/// <param name="mesh"></param> | |
/// <param name="vertices"></param> | |
public static void DrawMesh(this Mesh mesh, Vector3[] vertices) | |
{ | |
mesh.Clear(); | |
var count = vertices.Length; | |
var uvs = new Vector2[count]; | |
var triangles = new int[count]; | |
var _uvsForSegment = new Vector2[]{ | |
new Vector2(0, 0),new Vector2(1, 0),new Vector2(1, 1), | |
new Vector2(0, 0),new Vector2(1, 1),new Vector2(0, 1)}; | |
for (var i = 0; i < vertices.Length / 6; i++) | |
{ | |
var k = i * 6; | |
for (var j = 0; j < 6; j++) | |
{ | |
triangles[k + j] = k + j; | |
uvs[k + j] = _uvsForSegment[j]; | |
} | |
} | |
mesh.vertices = vertices; | |
mesh.uv = uvs; | |
mesh.triangles = triangles; | |
} | |
public static void DrawMesh(this Mesh mesh, Vector3[] vertices, Vector2[] uvs) | |
{ | |
mesh.Clear(); | |
var count = vertices.Length; | |
var uv = new Vector2[count]; | |
var triangles = new int[count]; | |
// var _uvsForSegment = new Vector2[]{ | |
// new Vector2(0, 0),new Vector2(1, 0),new Vector2(1, 1), | |
// new Vector2(0, 0),new Vector2(1, 1),new Vector2(0, 1)}; | |
for (var i = 0; i < vertices.Length / 6; i++) | |
{ | |
var k = i * 6; | |
for (var j = 0; j < 6; j++) | |
{ | |
triangles[k + j] = k + j; | |
uv[k + j] = uvs[j]; | |
} | |
} | |
mesh.vertices = vertices; | |
mesh.uv = uv; | |
mesh.triangles = triangles; | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment