using UnityEngine; using System.Collections; using System.IO; using SimpleJSON; using System.Text; using System; using UnityEngine.UI; using System.Text.RegularExpressions; public class Tools { //读取创建预制 public static GameObject createGameObject(string path) { if (path == null || path == "") return null; GameObject obj = null; try { obj = GameObject.Instantiate(Resources.Load(path)) as GameObject; NameReset(obj); } catch (System.Exception ex) { Debug.LogError(ex.ToString() + "!!!! path = " + path); } return obj; } public static GameObject createGameObjectTr(GameObject preObj, GameObject go) { GameObject obj = null; try { obj = GameObject.Instantiate(preObj) as GameObject; NameReset(obj); } catch (System.Exception ex) { Debug.LogError("!!!! path = "+ex); } try { obj.transform.SetParent(go.transform ); obj.transform.localPosition = Vector3.zero; obj.transform.localScale = new Vector3(1,1,1); obj.transform.localEulerAngles = Vector3.zero; } catch (System.Exception ex) { Debug.LogError("!!!! GO Tr = Null"+ex); } return obj; } //读取创建预制 并设置父类 public static GameObject createGameObjectTr(string path, GameObject go) { if (path == null || path == "") return null; GameObject preObj = (GameObject)Resources.Load(path); if (preObj == null ){ Debug.LogError("!!!! path = " + path ); return null; } return createGameObjectTr(preObj, go ); } //读取创建预制 并设置父类 public static GameObject CreateUI(string path, GameObject go) { if (path == null || path == "") return null; try { return CreateUI((GameObject)Resources.Load(path), go ); } catch (System.Exception ) { Debug.LogError("!!!! path = " + path); } return null; } //读取 UI 预制 并设置父类 public static GameObject createUITr(string path, Transform tr) { if (path == null || path == "") return null; GameObject obj = null; try { obj = GameObject.Instantiate(Resources.Load(path)) as GameObject; NameReset(obj); } catch (System.Exception) { Debug.LogError("!!!! path = " + path); } try { obj.transform.SetParent(tr); obj.transform.localPosition = Vector3.zero; obj.transform.localScale = Vector3.one; } catch (System.Exception) { Debug.LogError("!!!! GO Tr = Null"); } return obj; } //读取创建预制 并设置父类 public static GameObject CreateUI(GameObject preUI, GameObject go) { if (preUI == null) return null; GameObject obj = null; try { obj = GameObject.Instantiate(preUI) as GameObject; NameReset(obj); } catch (System.Exception ex) { Debug.LogError("!!!! preUI null = "+ex ); } // try // { obj.transform.SetParent(go.transform ); RectTransform rectTransform = obj.GetComponent(); if (rectTransform != null ){ rectTransform.offsetMax = new Vector2(0,0); rectTransform.offsetMin = new Vector2(0,0); obj.transform.localPosition = Vector3.zero; obj.transform.localScale = new Vector3(1,1,1); // rectTransform.TransformPoint(0, 0, 0); // rectTransform.position = Vector3.zero; }else{ obj.transform.localPosition = Vector3.zero; obj.transform.localScale = new Vector3(1,1,1); } // } // catch (System.Exception ex) // { // Debug.LogError("!!!! GO Tr = Null"); // } return obj; } // 读取对象 Object public static UnityEngine.Object LoadResources(string path) { UnityEngine.Object obj = Resources.Load(path); if (obj == null) return null; UnityEngine.Object go = UnityEngine.Object.Instantiate(obj); return path != null ? go : null; } //创建物体并设置贴图及增加组件 public static GameObject SetObjectProperty(GameObject obj, Texture2D tex,Transform tr,string path) { try { obj.transform.parent = tr.parent.Find(path); obj.transform.localScale = Vector3.one; obj.GetComponent().sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); obj.GetComponent().color = new Color(1, 1, 1, 1); obj.GetComponent().sizeDelta = new Vector2(tex.width, tex.height); obj.GetComponent().size = new Vector2(tex.width, tex.height); obj.GetComponent().isTrigger = true; obj.GetComponent().gravityScale = 0; } catch { Debug.LogError("预制件组件缺失,请先增加"); } return obj; } // 修改替换 图片 public static void SetObjectImage(GameObject go, string path, string img_path) { try { Sprite temp = Resources.Load(img_path, typeof(Sprite)) as Sprite; go.transform.Find(path).GetComponent().overrideSprite = temp; } catch { Debug.LogError("!!!替换图片出错 == " + go.name + " || " + path + " ||" + img_path); } } // 修改替换 图片 public static void SetImageToImage(Image img, string img_path) { try { Sprite temp = Resources.Load(img_path, typeof(Sprite)) as Sprite; img.sprite = temp; } catch { Debug.LogError("!!!替换图片出错 == " + img.name + " ||" + img_path); } } // 修改替换 图片 public static void SetObjectImage(GameObject go, string img_path) { try { Sprite temp = Resources.Load(img_path, typeof(Sprite)) as Sprite; go.GetComponent().overrideSprite = temp; } catch { Debug.LogWarning("!!!替换图片出错 == " + go.name + " ||" + img_path); } } public static Sprite SetPathToSprite(string path) { Texture2D tex = new Texture2D(100, 100); try { tex = (Texture2D)Resources.Load(path, typeof(Texture2D)); } catch (System.Exception) { Debug.LogError("!!!! tex = Null path =" + path); return null; } Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); return sp; } public static Sprite SetTexToSprite(Texture2D tex) { Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); return sp; } //读取 2D 纹理 public static Texture2D LoadTexture2D(string path) { Texture2D tex = new Texture2D(100, 100); try { tex = (Texture2D)Resources.Load(path, typeof(Texture2D)); } catch (System.Exception ) { Debug.LogError("!!!! tex = Null path =" + path); return null; } return tex; } //返回 text public static Text GetUGUI_Text(GameObject go, string path = null) { if (go == null) { return null; } Text text; if (string.IsNullOrEmpty(path)) { text = go.GetComponent(); } else text = go.transform.Find(path).GetComponent(); return text; } public static Text GetUGUI_Text(Transform go, string path = null) { if (go == null) { return null; } Text text; if (string.IsNullOrEmpty(path)) { text = go.GetComponent(); } else text = go.Find(path).GetComponent(); return text; } //返回 Image public static Image GetUGUI_Image(GameObject go, string path = null) { if (go == null) { return null; } Image img; if (string.IsNullOrEmpty(path)) { img = go.GetComponent(); } else img = go.transform.Find(path).GetComponent(); return img; } public static Image GetUGUI_Image(Transform go, string path = null) { if (go == null) { return null; } Image img; if (string.IsNullOrEmpty(path)) { img = go.GetComponent(); } else img = go.Find(path).GetComponent(); return img; } public static Sprite TexToSprite(Texture2D tex) { if (tex == null) { return null; } Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); return sp; } //两个Text 首尾相连 public static void SetTextToTextPosition(Transform tr, Transform tr2) { float width = tr.GetComponent().sizeDelta.x; float x = tr.localPosition.x; tr2.localPosition = new Vector3(x + width, tr2.localPosition.y, 0); } //重置 预制件名字 public static void NameReset(GameObject go) { int fpos = go.name.IndexOf("("); if (fpos >= 0) { go.name = go.name.Substring(0, fpos); } } public static string NameReset(string name) { int fpos = name.IndexOf("("); if (fpos >= 0) { name = name.Substring(0, fpos); } return name; } public static Vector3 RandomPos(Vector2 x,Vector2 y,Vector2 z) { float X = UnityEngine.Random.Range(x.x, x.y); float Y = UnityEngine.Random.Range(y.x, y.y); float Z = UnityEngine.Random.Range(z.x, z.y); Vector3 pos = new Vector3(X, Y, Z); return pos; } //秒 转 小时 分 秒 public static string FormatTime_H(int seconds) { int intH = seconds / 3600; string strH = intH < 10 ? "0" + intH.ToString() : intH.ToString(); int intM = (seconds % 3600) / 60; string strM = intM < 10 ? "0" + intM.ToString() : intM.ToString(); int intS = seconds % 3600 % 60; string strS = intS < 10 ? "0" + intS.ToString() : intS.ToString(); return strH + ":" + strM + ":" + strS; } //秒 转 分 秒 public static string FormatTime_M(int seconds) { int intM = seconds / 60; string strM = intM < 10 ? "0" + intM.ToString() : intM.ToString(); int intS = seconds % 60; string strS = intS < 10 ? "0" + intS.ToString() : intS.ToString(); return strM + ":" + strS; } //毫秒 转 分 秒 毫秒 public static string FormatTime_MS(int seconds) { TimeSpan ss = new TimeSpan(0, 0, 0, 0, (int)seconds); string timeString = string.Format("{0}:{1}.{2}", ss.Minutes.ToString("00"), ss.Seconds.ToString("00"), ss.Milliseconds.ToString("00").Substring(0,2)); return timeString; } // 颜色字符(0xffffffff)转换 color public static Color ColorFromString(string colorstring) { int r = VFromChar(colorstring[0]) * 16 + VFromChar(colorstring[1]); int g = VFromChar(colorstring[2]) * 16 + VFromChar(colorstring[3]); int b = VFromChar(colorstring[4]) * 16 + VFromChar(colorstring[5]); int a = VFromChar(colorstring[6]) * 16 + VFromChar(colorstring[7]); return new UnityEngine.Color(r * 1f / 255, g * 1f / 255, b * 1f / 255, a * 1f / 255); } static int VFromChar(int c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } else { return c - 'a' + 10; } } // 3D物体在2D屏幕上的位置 public static Vector3 GetUIPosBy3DGameObj(GameObject gobj3d, Camera camer3d, Camera camera2d, float z, float y) { Vector3 v1 = camer3d.WorldToViewportPoint(new Vector3(gobj3d.transform.position.x, y, gobj3d.transform.position.z)); Vector3 v2 = camera2d.ViewportToWorldPoint(v1); v2.z = z; return v2; } //设置2d物体 到 3D物体在屏幕上的位置 public static void SetUIPosBy3DGameObj(GameObject gobj2d, GameObject gobj3d, Camera camer3d, Camera camera2d, float z, Vector3 offset) { Vector3 v1 = camer3d.WorldToViewportPoint(gobj3d.transform.position); Vector3 v2 = camera2d.ViewportToWorldPoint(v1); v2.z = z; gobj2d.transform.position = v2 + offset; } //返回物体内名字为 “” 的gameobject static GameObject findGo = null; public static GameObject GetNameFindGameObject(GameObject go, string name) { findGo = null; GetFindGameObjectName(go, name); if (findGo != null) { return findGo; } return findGo; } static void GetFindGameObjectName(GameObject go, string name) { bool find = false; for (int i = 0; i < go.transform.childCount; i++) { if (go.transform.GetChild(i).name == name) { find = true; findGo = go.transform.GetChild(i).gameObject; return; } } if (!find) { for (int i = 0; i < go.transform.childCount; i++) { if (go.transform.GetChild(i).childCount > 0) { GetFindGameObjectName(go.transform.GetChild(i).gameObject, name); } } } } //写 二进制文件 public static void WriteBytes(string path, byte[] bytes){ FileStream fs = new FileStream(path, FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); } //写 txt文件 public static void WriteTxt(string path, string text) { FileStream fs = new FileStream(path, FileMode.Create); byte[] data = System.Text.Encoding.UTF8.GetBytes(text.ToString()); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } //删除文件 public static void RemoveTxt(string path) { File.Delete(path); } // 项目内部 读文件 String public static string LoadGameString(string path) { string txt = ((TextAsset)Resources.Load(path)).text; return txt; } // 项目内部 读文件 json public static JSONNode LoadGameJson(string path) { string txt = ((TextAsset)Resources.Load(path)).text; JSONNode json = JSONClass.Parse(txt); return json; } //项目内 读取二进制文件 public static byte[] LoadBytes(string path) { FileStream file = new FileStream(path, FileMode.Open); int len = (int)file.Length; byte[] byData = new byte[len]; file.Read(byData, 0, len); file.Close(); return byData; } //外部 读txt文件 public static string LoadString(string path) { FileStream file = new FileStream(path, FileMode.Open); int len = (int)file.Length; byte[] byData = new byte[len]; file.Read(byData, 0, len); string text = Encoding.UTF8.GetString(byData); file.Close(); return text; } //外部获取某个文件夹下某张图片并转换成sprite public static Sprite PathToSprite(string path,int i,Sprite src) { try { DirectoryInfo d = new DirectoryInfo(path); FileSystemInfo[] fsinfos = d.GetFileSystemInfos(); byte[] bytes = Tools.LoadBytes(fsinfos[i].FullName); Texture2D tex = new Texture2D(100, 100); tex.LoadImage(bytes); Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); src = sp; } catch (Exception) { Debug.Log("没有相对于的鱼"); } return src; } //字符串是否 有中文字 public static bool IsChinese(string text) { for (int i = 0; i < text.Length; i++ ) { if (System.Text.RegularExpressions.Regex.IsMatch(text[i].ToString(), @"^[\u4e00-\u9fa5]+$")) { return true; } } return false; } //字符串是否 有 特殊符号 public static bool IsSymbol(string text) { for (int i = 0; i < text.Length; i++) { if (!char.IsLetter(text[i]) && !char.IsNumber(text[i])) { return true; } } return false; } //字符串长度(中文字为2个字符) public static int GetStringLength(string text) { int num = 0; for (int i = 0; i < text.Length; i++) { if (System.Text.RegularExpressions.Regex.IsMatch(text[i].ToString(), @"^[\u4e00-\u9fa5]+$")) { num++; } } return text.Length + num; } // 中英字 是否超出长度 public static bool IsStringLength(string text, int num) { if (text.Length > num) return true; int temp = 0; for (int i = 0; i < text.Length; i++) { if (System.Text.RegularExpressions.Regex.IsMatch(text[i].ToString(), @"^[\u4e00-\u9fa5]+$")) { temp++; } } if (text.Length + temp > num) { return true; } return false; } //字符串 是否 纯数字 public static bool IsNumber(string str) { for (int i = 0; i < str.Length; i++ ) { if (!Char.IsNumber(str, i)) { return false; } } return true; } // 是否 是正确 的邮箱地址 public static bool IsEmail(string str_email) { return System.Text.RegularExpressions.Regex.IsMatch(str_email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } //获取时间戳 public static string GetTimeStamp_MS() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } //解析时间戳 public static string[] GetTimeStamp_ch(long timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = ((long)timeStamp * 10000); TimeSpan toNow = new TimeSpan(lTime); DateTime dtResult = dtStart.Add(toNow); string date = dtResult.ToShortDateString().ToString(); string time = dtResult.ToString("HH:mm:ss"); string[] date_arr = date.Split('/'); string[] time_arr = time.Split(':'); string secondarr = time_arr[2]; char[] second = secondarr.ToCharArray(); string[] result = new string[]{ date_arr[2] + "年" + date_arr[0] + "月" + date_arr[1] + "日", time_arr[0] + ":" +time_arr[1] + ":" + second[0] + second[1]}; return result; } public static string[] GetTimeCountDown(long overtime) { long nowTime = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds); long timef = (overtime - nowTime) / 1000; string[] time = new string[4]; time[0] = Math.Floor((float)(timef / 86400)).ToString(); timef -= int.Parse(time[0]) * 86400; time[1] = Math.Floor((float)(timef / 3600)).ToString(); timef -= int.Parse(time[1]) * 3600; time[2] = Math.Floor((float)(timef / 60)).ToString(); timef -= int.Parse(time[2]) * 60; time[3] = timef.ToString(); return time; } public static string GetTimeStamp(long _time) { long timeStamp = _time; System.DateTime dtStart = System.TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); Debug.LogWarning(timeStamp); long lTime =long.Parse(timeStamp+"0000000"); System.TimeSpan toNow = new System.TimeSpan(lTime); System.DateTime dtResult = dtStart.Add(toNow); string date = dtResult.ToShortDateString().ToString(); string[] date_arr = date.Split('/'); string result = (date_arr[2] + "/" + date_arr[0] + "/" + date_arr[1]); return result; } public static string GetTimeFormat(int second) { TimeSpan ts = new TimeSpan(0, 0, second); return string.Format("{0:d2}:{1:d2}:{2:d2}",(int)ts.TotalHours, ts.Minutes, ts.Seconds); } public static string[] GetTimeStamp(string _time) { long timeStamp = long.Parse(_time); System.DateTime dtStart = System.TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); long lTime = timeStamp * 10000000; System.TimeSpan toNow = new System.TimeSpan(lTime); System.DateTime dtResult = dtStart.Add(toNow); string date = dtResult.ToShortDateString().ToString(); string time = dtResult.ToString("HH:mm:ss"); string[] date_arr = date.Split('/'); string[] time_arr = time.Split(':'); string secondarr = time_arr[2]; char[] second = secondarr.ToCharArray(); string[] result = new string[]{ date_arr[2] + "/" + date_arr[0] + "/" + date_arr[1], time_arr[0] + ":" +time_arr[1] + ":" + second[0] + second[1]}; return result; } public static T GetOrCreateComponent(GameObject go ) where T : Component{ if (go.GetComponent()==null){ return go.AddComponent(); } return go.GetComponent(); } public static GameObject FindGoByID(GameObject parent, string childName) { if(parent.name == childName) { return parent; } if(parent.transform.childCount < 1) { return null; } GameObject obj = null; for(int i = 0;i(GameObject parent, string childName) where Com : Component{ if(parent.name == childName) { return parent.GetComponent(); } Com[] childs = parent.GetComponentsInChildren(true ); foreach(Com child in childs ){ if (child.gameObject.name == childName ){ return child; } } return null; } public static void ActiveAll(GameObject parent, bool isActive ){ Transform[] allTrans = parent.GetComponentsInChildren(true); foreach(Transform child in allTrans ){ if (child.gameObject.activeSelf!=isActive ){ child.gameObject.SetActive(isActive ); } } } public static void ActiveChildren(GameObject parent, GameObject exceptGo, bool isActive ){ for (int i = 0; i < parent.transform.childCount; i++ ){ Transform child = parent.transform.GetChild(i); if (child.gameObject == exceptGo ){ continue; } child.gameObject.SetActive(isActive ); } } public static bool ObjectIsInArray(T target, T[] targetArray) { for (int i = 0; i < targetArray.Length; i++) { if (target.Equals(targetArray[i])) return true; } return false; } public static void SetParent(GameObject target, GameObject parent ){ Vector3 orginPosition = target.transform.localPosition; Vector3 orginAngles = target.transform.localEulerAngles; Vector3 orginScale = target.transform.localScale; target.transform.SetParent(parent.transform); target.transform.localEulerAngles = orginAngles; target.transform.localScale = orginScale; target.transform.localPosition = orginPosition; } public static bool IsAnimatorPlay(Animator animator ){ return animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1; } public static IEnumerator DelayExecute(float time, Action del) { yield return new WaitForSeconds(time); if (del != null) del(); } /** unit: ms */ public static long GetRealTick(){ long curUnixTime = DateTime.UtcNow.ToFileTimeUtc(); DateTime date70 = new DateTime(1970, 1, 1, 0, 0, 0); long fileTime70 = curUnixTime - date70.ToFileTimeUtc(); return fileTime70/10000; } } public class Gow{ private GameObject mGo; public static Gow c(GameObject go ){ Gow gow = new Gow(); gow.mGo = go; return gow; } public GameObject Find(string childName) { Transform trans = Find(childName); if (trans != null ){ return trans.gameObject; } RectTransform rectTrans = Find(childName); if (rectTrans != null ){ return rectTrans.gameObject; } return null; } public Com Find(string childName) where Com : Component{ if(mGo.name == childName) { return mGo.GetComponent(); } Com[] childs = mGo.GetComponentsInChildren(true ); foreach(Com child in childs ){ //Debug.Log("name is " + child.gameObject.name ); if (child.gameObject.name == childName ){ return child; } } return null; } public void Normalize(GameObject parent ){ mGo.transform.parent = parent.transform; mGo.transform.localPosition = Vector3.zero; mGo.transform.localEulerAngles = Vector3.zero; mGo.transform.localScale = new Vector3(1,1,1); } public void ActiveAll(bool isActive ){ Transform[] allTrans = mGo.GetComponentsInChildren(true ); foreach(Transform trans in allTrans ){ trans.gameObject.SetActive(isActive ); } } public void PostPrefab(GameObject prefab ){ Transform prefabsParent = mGo.transform.Find("ym_prefabs_parent"); if (prefabsParent == null ){ GameObject go = new GameObject("ym_prefabs_parent"); Tools.SetParent(go, mGo ); prefabsParent = go.transform; prefabsParent.SetAsLastSibling(); } Tools.SetParent(prefab, prefabsParent.gameObject ); prefab.SetActive(false ); } public GameObject GetOrCreateGo(string name ){ Transform childTrans = mGo.transform.Find(name); if (childTrans == null ){ GameObject go = new GameObject(name ); Tools.SetParent(go, mGo ); childTrans = go.transform; } return childTrans.gameObject; } }