今天小編給大家分享一下Unity全局工具類有哪些的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
創(chuàng)新互聯(lián)建站專注于企業(yè)成都營銷網(wǎng)站建設(shè)、網(wǎng)站重做改版、烏拉特后網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5高端網(wǎng)站建設(shè)、商城建設(shè)、集團公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為烏拉特后等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
public static string GetLocalIP() { //DNS.GetHostName()獲取本機名Dns.GetHostAddresses()根據(jù)本機名獲取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("當(dāng)前文件的大小: " + 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對像 // 加密后是一個字節(jié)類型的數(shù)組,這里要注意編碼UTF8/Unicode等的選擇 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); // 通過使用循環(huán),將字節(jié)類型的數(shù)組轉(zhuǎn)換為字符串,此字符串是常規(guī)字符格式化所得 for (int i = 0; i < s.Length; i++) { // 將得到的字符串使用十六進(jìn)制類型格式。格式后的字符是小寫的字母,如果使用大寫(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 控件添加事件監(jiān)聽 /// </summary> /// <param name="target">事件監(jiān)聽目標(biāo)</param> /// <param name="type">事件類型</param> /// <param name="callback">回調(diào)函數(shù)</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(); //設(shè)置事件類型 entry.eventID = type; //設(shè)置事件回調(diào)函數(shù) entry.callback = new EventTrigger.TriggerEvent(); entry.callback.AddListener(callback); //添加事件到事件組 trigger.triggers.Add(entry); }
// UGUI Button添加點擊事件監(jiān)聽 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移除所有事件監(jiān)聽 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內(nèi)容的長度在length以內(nèi),超過的部分用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> /// 世界坐標(biāo)轉(zhuǎn)換為UGUI坐標(biāo)(只針對框架UI模塊下的UI控件) /// </summary> /// <param name="position">世界坐標(biāo)</param> /// <param name="reference">參照物(要賦值的UGUI控件的根物體)</param> /// <param name="uIType">UI類型</param> /// <returns>基于參照物的局部UGUI坐標(biāo)</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> /// 屏幕坐標(biāo)轉(zhuǎn)換為UGUI坐標(biāo)(只針對框架UI模塊下的UI控件) /// </summary> /// <param name="position">屏幕坐標(biāo)</param> /// <param name="reference">參照物(要賦值的UGUI控件的根物體)</param> /// <param name="uIType">UI類型</param> /// <returns>基于參照物的局部UGUI坐標(biāo)</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標(biāo)簽查找場景中指定物 public static GameObject FindObjectByTag(string tagName) { return GameObject.FindGameObjectWithTag(tagName); }
//設(shè)置所有子物體的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); } }
//寫進(jìn)去 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:幾率數(shù)組(%), 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:幾率數(shù)組(%), 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全局工具類有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站欄目:Unity全局工具類有哪些
本文URL:http://jinyejixie.com/article32/pdcgpc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站、移動網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)