Unity全局工具类有哪些
今天小编给大家分享一下Unity全局工具类有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
创新互联建站专注于企业成都营销网站建设、网站重做改版、乌拉特后网站定制设计、自适应品牌网站建设、H5高端网站建设、商城建设、集团公司官网建设、成都外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为乌拉特后等各大城市提供网站开发制作服务。
一:系统工具
一:获取本机IP地址
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; }
二:获取本机MAC地址
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
// 计算字符串的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; }
四:计算文件的MD5
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位加密
// 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编码解码
// 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; }
二:UI控件常用功能及事件监听
一:UI控件添加事件监听
////// UGUI 控件添加事件监听 /// /// 事件监听目标 /// 事件类型 /// 回调函数 public static void AddEventListener(this RectTransform target, EventTriggerType type, UnityActioncallback) { EventTrigger trigger = target.GetComponent (); if (trigger == null) { trigger = target.gameObject.AddComponent (); trigger.triggers = new List (); } //定义一个事件 EventTrigger.Entry entry = new EventTrigger.Entry(); //设置事件类型 entry.eventID = type; //设置事件回调函数 entry.callback = new EventTrigger.TriggerEvent(); entry.callback.AddListener(callback); //添加事件到事件组 trigger.triggers.Add(entry); }
二:UGUI按钮添加移除点击监听事件
// UGUI Button添加点击事件监听 public static void AddEventListener(this RectTransform target, UnityAction callback) { Button button = target.GetComponent
三:判定鼠标是否停留在ui控件上
public static bool IsPointerOverUGUI() { if (EventSystem.current) { return EventSystem.current.IsPointerOverGameObject(); } else { return false; } }
四:限制Text内容的长度
// 限制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内指定内容的大小颜色加粗斜体
// 限制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, ""); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, " "); 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, ""); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, " "); 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, ""); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, ""); 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, ""); else return; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, ""); 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 { ////// 屏幕UI /// Overlay, ////// 摄像机UI /// Camera, ////// 世界UI /// World }
一:世界坐标转换为UGUI坐标
////// 世界坐标转换为UGUI坐标(只针对框架UI模块下的UI控件) /// /// 世界坐标 /// 参照物(要赋值的UGUI控件的根物体) /// UI类型 ///基于参照物的局部UGUI坐标 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; }
二:屏幕坐标转换为UGUI坐标
////// 屏幕坐标转换为UGUI坐标(只针对框架UI模块下的UI控件) /// /// 屏幕坐标 /// 参照物(要赋值的UGUI控件的根物体) /// UI类型 ///基于参照物的局部UGUI坐标 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(GameObject goParent, string childName) where T : Component { Transform searchTrans = FindTheChild(goParent, childName); if (searchTrans != null) { return searchTrans.gameObject.GetComponent (); } 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; }
四:通过组件查找场景中所有的物体,包括隐藏和激活的
////// 通过组件查找场景中所有的物体,包括隐藏和激活的 /// ///组件类型 /// 组件列表 public static void FindObjectsOfType(List Result) where T : Component { if (Result == null) Result = new List (); else Result.Clear(); List sub = new List (); GameObject[] rootObjs = SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject rootObj in rootObjs) { rootObj.transform.GetComponentsInChildren(true, sub); Result.AddRange(sub); } }
五:通过Tag标签查找
//通过Tag标签查找场景中指定物 public static GameObject FindObjectByTag(string tagName) { return GameObject.FindGameObjectWithTag(tagName); }
六:设置所有子物体的Layer
//设置所有子物体的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); } }
五:文件IO操作
一:写文件
//写进去 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全局工具类有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注创新互联行业资讯频道。
本文题目:Unity全局工具类有哪些
网页网址:http://ybzwz.com/article/pdcgpc.html