您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
今天小编给大家分享一下Unity全局工具类有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
public static string GetLocalIP() { //Dns.GetHostName()获取本机名Dns.GetHostAddresses()根据本机名获取ip地址组 IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ip in ips) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); //ipv4 } } return null; }
public static string GetMacAddress() { try { NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0; i < nis.Length; i++) { if (nis[i].Name == "本地连接") { return nis[i].GetPhysicalAddress().ToString(); } } return "null"; } catch { return "null"; } }
// 计算字符串的MD5值 public static string Md5String(string source) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.UTF8.GetBytes(source); byte[] md5Data = md5.ComputeHash(data, 0, data.Length); md5.Clear(); string destString = ""; for (int i = 0; i < md5Data.Length; i++) { destString += System.Convert.ToString(md5Data[i], 16).PadLeft(2, '0'); } destString = destString.PadLeft(32, '0'); return destString; }
public static string Md5File(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); string size = fs.Length / 1024 + ""; //Debug.Log("当前文件的大小: " + file + "===>" + (fs.Length / 1024) + "KB"); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb + "|" + size; } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } }
// MD5 32位加密 public static string UserMd5(string str) { string cl = str; StringBuilder pwd = new StringBuilder(); MD5 md5 = MD5.Create();//实例化一个md5对像 // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得 for (int i = 0; i < s.Length; i++) { // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 pwd.Append(s[i].ToString("x2")); //pwd = pwd + s[i].ToString("X"); } return pwd.ToString(); }
public static void Encypt(ref byte[] targetData, byte m_key) { //加密,与key异或,解密的时候同样如此 int dataLength = targetData.Length; for (int i = 0; i < dataLength; ++i) { targetData[i] = (byte)(targetData[i] ^ m_key); } }
// Base64编码 public static string Encode(string message) { byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(message); return Convert.ToBase64String(bytes); } // Base64解码 public static string Decode(string message) { byte[] bytes = Convert.FromBase64String(message); return Encoding.GetEncoding("utf-8").GetString(bytes); }
public static string RandomCharacters() { string str = string.Empty; long num2 = DateTime.Now.Ticks + 0; System.Random random = new System.Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> 1))); for (int i = 0; i < 20; i++) { char ch; int num = random.Next(); if ((num % 2) == 0) { ch = (char)(0x30 + ((ushort)(num % 10))); } else { ch = (char)(0x41 + ((ushort)(num % 0x1a))); } str = str + ch.ToString(); } return str; }
/// <summary> /// UGUI 控件添加事件监听 /// </summary> /// <param name="target">事件监听目标</param> /// <param name="type">事件类型</param> /// <param name="callback">回调函数</param> public static void AddEventListener(this RectTransform target, EventTriggerType type, UnityAction<BaseEventData> callback) { EventTrigger trigger = target.GetComponent<EventTrigger>(); if (trigger == null) { trigger = target.gameObject.AddComponent<EventTrigger>(); trigger.triggers = new List<EventTrigger.Entry>(); } //定义一个事件 EventTrigger.Entry entry = new EventTrigger.Entry(); //设置事件类型 entry.eventID = type; //设置事件回调函数 entry.callback = new EventTrigger.TriggerEvent(); entry.callback.AddListener(callback); //添加事件到事件组 trigger.triggers.Add(entry); }
// UGUI Button添加点击事件监听 public static void AddEventListener(this RectTransform target, UnityAction callback) { Button button = target.GetComponent<Button>(); if (button) { button.onClick.AddListener(callback); } else { Debug.Log(target.name + " 丢失了组件 Button!"); } } // UGUI Button移除所有事件监听 public static void RemoveAllEventListener(this RectTransform target) { Button button = target.GetComponent<Button>(); if (button) { button.onClick.RemoveAllListeners(); } else { Debug.Log(target.name + " 丢失了组件 Button!"); } }
public static bool IsPointerOverUGUI() { if (EventSystem.current) { return EventSystem.current.IsPointerOverGameObject(); } else { return false; } }
// 限制Text内容的长度在length以内,超过的部分用replace代替 public static void RestrictLength(this Text tex, int length, string replace) { if (tex.text.Length > length) { tex.text = tex.text.Substring(0, length) + replace; } }
// 限制Text中指定子字串的字体大小 public static void ToRichSize(this Text tex, string subStr, int size) { if (subStr.Length <= 0 || !tex.text.Contains(subStr)) { return; } string valueRich = tex.text; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<size=" + size + ">"); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</size>"); else return; tex.text = valueRich; } // 限制Text中指定子字串的字体颜色 public static void ToRichColor(this Text tex, string subStr, Color color) { if (subStr.Length <= 0 || !tex.text.Contains(subStr)) { return; } string valueRich = tex.text; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<color=" + color.ToHexSystemString() + ">"); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</color>"); else return; tex.text = valueRich; } // 限制Text中的指定子字串的字体加粗 public static void ToRichBold(this Text tex, string subStr) { if (subStr.Length <= 0 || !tex.text.Contains(subStr)) { return; } string valueRich = tex.text; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<b>"); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</b>"); else return; tex.text = valueRich; } // 限制Text中的指定子字串的字体斜体 public static void ToRichItalic(this Text tex, string subStr) { if (subStr.Length <= 0 || !tex.text.Contains(subStr)) { return; } string valueRich = tex.text; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<i>"); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</i>"); else return; tex.text = valueRich; } // 清除所有富文本样式 public static void ClearRich(this Text tex) { string value = tex.text; for (int i = 0; i < value.Length; i++) { if (value[i] == '<') { for (int j = i + 1; j < value.Length; j++) { if (value[j] == '>') { int count = j - i + 1; value = value.Remove(i, count); i -= 1; break; } } } } tex.text = value; }
public enum UIType { /// <summary> /// 屏幕UI /// </summary> Overlay, /// <summary> /// 摄像机UI /// </summary> Camera, /// <summary> /// 世界UI /// </summary> World }
/// <summary> /// 世界坐标转换为UGUI坐标(只针对框架UI模块下的UI控件) /// </summary> /// <param name="position">世界坐标</param> /// <param name="reference">参照物(要赋值的UGUI控件的根物体)</param> /// <param name="uIType">UI类型</param> /// <returns>基于参照物的局部UGUI坐标</returns> public static Vector2 WorldToUGUIPosition(this Vector3 position, RectTransform reference = null, UIType uIType = UIType.Overlay) { Vector3 screenPos; Vector2 anchoredPos = Vector2.zero; switch (uIType) { case UIType.Overlay: screenPos = Camera.main.WorldToScreenPoint(position); screenPos.z = 0; RectTransformUtility.ScreenPointToLocalPointInRectangle(reference, screenPos, null, out anchoredPos); break; case UIType.Camera: screenPos = Camera.main.WorldToScreenPoint(position); screenPos.z = 0; RectTransformUtility.ScreenPointToLocalPointInRectangle(reference, screenPos, Camera.main, out anchoredPos); break; case UIType.World: break; } return anchoredPos; }
/// <summary> /// 屏幕坐标转换为UGUI坐标(只针对框架UI模块下的UI控件) /// </summary> /// <param name="position">屏幕坐标</param> /// <param name="reference">参照物(要赋值的UGUI控件的根物体)</param> /// <param name="uIType">UI类型</param> /// <returns>基于参照物的局部UGUI坐标</returns> public static Vector2 ScreenToUGUIPosition(this Vector3 position, RectTransform reference = null, UIType uIType = UIType.Overlay) { Vector2 anchoredPos = Vector2.zero; switch (uIType) { case UIType.Overlay: position.z = 0; RectTransformUtility.ScreenPointToLocalPointInRectangle(reference, position, null, out anchoredPos); break; case UIType.Camera: position.z = 0; RectTransformUtility.ScreenPointToLocalPointInRectangle(reference, position, Camera.main, out anchoredPos); break; case UIType.World: break; } return anchoredPos; }
//查找物体的方法 public static Transform FindTheChild(GameObject goParent, string childName) { Transform searchTrans = goParent.transform.Find(childName); if (searchTrans == null) { foreach (Transform trans in goParent.transform) { searchTrans = FindTheChild(trans.gameObject, childName); if (searchTrans != null) { return searchTrans; } } } return searchTrans; }
//获取子物体的脚本 public static T GetTheChildComponent<T>(GameObject goParent, string childName) where T : Component { Transform searchTrans = FindTheChild(goParent, childName); if (searchTrans != null) { return searchTrans.gameObject.GetComponent<T>(); } else { return null; } }
// 查找兄弟 public static GameObject FindBrother(this GameObject obj, string name) { GameObject gObject = null; if (obj.transform.parent) { Transform tf = obj.transform.parent.Find(name); gObject = tf ? tf.gameObject : null; } else { GameObject[] rootObjs = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject rootObj in rootObjs) { if (rootObj.name == name) { gObject = rootObj; break; } } } return gObject; }
/// <summary> /// 通过组件查找场景中所有的物体,包括隐藏和激活的 /// </summary> /// <typeparam name="T">组件类型</typeparam> /// <param name="Result">组件列表</param> public static void FindObjectsOfType<T>(List<T> Result) where T : Component { if (Result == null) Result = new List<T>(); else Result.Clear(); List<T> sub = new List<T>(); GameObject[] rootObjs = SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject rootObj in rootObjs) { rootObj.transform.GetComponentsInChildren(true, sub); Result.AddRange(sub); } }
//通过Tag标签查找场景中指定物 public static GameObject FindObjectByTag(string tagName) { return GameObject.FindGameObjectWithTag(tagName); }
//设置所有子物体的Layer public static void SetLayer(int parentLayer, Transform childTrs) { childTrs.gameObject.layer = parentLayer; for (int i = 0; i < childTrs.childCount; i++) { Transform child = childTrs.GetChild(i); child.gameObject.layer = parentLayer; SetLayer(parentLayer, child); } }
//写进去 public static void WriteFile(string pathName, string info) { StreamWriter sw; FileInfo fi = new FileInfo(pathName); sw = fi.CreateText(); sw.WriteLine(info); sw.Close(); sw.Dispose(); }
//读出来 public static string ReadFile(string pathName) { StreamReader sr; FileInfo fi = new FileInfo(pathName); sr = fi.OpenText(); string info = sr.ReadToEnd(); sr.Close(); sr.Dispose(); return info; }
/**加*/ //rate:几率数组(%), total:几率总和(100%) // Debug.Log(rand(new int[] { 10, 5, 15, 20, 30, 5, 5,10 }, 100)); public static int rand(int[] rate, int total) { int r = UnityEngine.Random.Range(1, total + 1); int t = 0; for (int i = 0; i < rate.Length; i++) { t += rate[i]; if (r < t) { return i; } } return 0; } /**减*/ //rate:几率数组(%), total:几率总和(100%) // Debug.Log(randRate(new int[] { 10, 5, 15, 20, 30, 5, 5,10 }, 100)); public static int randRate(int[] rate, int total) { int rand = UnityEngine.Random.Range(0, total + 1); for (int i = 0; i < rate.Length; i++) { rand -= rate[i]; if (rand <= 0) { return i; } } return 0; }
以上就是“Unity全局工具类有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。