推荐阅读

一、导言

在开发中,我们会将调用次数比较多的函数单独提出来写到一个类中,比如字符串转16进制,给字符串加密这些都是比较常用的,就可以将这些常用的函数提取出来,放到工具类中,方便调用

二、工具类

2-1、查找对象

根据父物体对象,找到指定名字的子物体,返回GameObject对象

//child 是要查询的物体的父节点,name是要查询的子物体的名字
    public static GameObject Find(GameObject child, string name)
    {
        //定义一个Transform 变量it用来接收查询到子物体
        Transform it = child.transform.Find(name);
        if (it != null)
        {
            return it.gameObject;
        }
        if (child.transform.childCount == 0)
        {
            return null;
        }
        //查找子对象的子对象
        for (int i = 0; i < child.transform.childCount; i++)
        {
            //递归查询  定义一个Transform 变量its用来接收查询到子物体
            GameObject its = Find(child.transform.GetChild(i).gameObject, name);
            //如果不为空,就是存在次物体返回该物体
            if (its != null)
            {
                return its.gameObject;
            }
        }
        return null;
    }

根据父物体对象,找到指定组件的指定的名字的子对象,返回的是指定组件的对象

//child 是要查询的物体的父节点,name是要查询的子物体的名字 返回的是一个泛型
    public static T Find<T>(GameObject child, string name)
    {
        //定义一个Transform 变量it用来接收查询到子物体
        Transform it = child.transform.Find(name);
        if (it != null)
        {
            return it.GetComponent<T>();
        }
        if (child.transform.childCount == 0)
        {
            return default;
        }
        //查找子对象的子对象
        for (int i = 0; i < child.transform.childCount; i++)
        {
            //递归查询  定义一个Transform 变量its用来接收查询到子物体
            GameObject its = Find(child.transform.GetChild(i).gameObject, name);
            //如果不为空,就是存在次物体返回该物体
            if (its != null)
            {
                return its.GetComponent<T>();
            }
        }
        return default;
    }

根据名字,返回指定名字下的组件

/// <summary>
    /// 获取物体名下的 T 组件
    /// </summary>
    /// <param name="namestring">物体名</param>
    /// <returns></returns>
    public static T FindT<T>(string namestring)
    {
        return GameObject.Find(namestring).GetComponent<T>();
    }

根据名字,返回指定Button组件

 /// <summary>
    /// 获取Button组件
    /// </summary>
    /// <param name="namestring"></param>
    /// <returns></returns>
    public static Button FindBtn(string namestring)
    {
        return GameObject.Find(namestring).GetComponent<Button>();
    }

2-2、对文本的处理

将数组中的所有字符按照特定分隔符拼接

/// <summary>
    /// 将一个数组转换为一个字符串,按特定的分隔符拼接
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="tarray"></param>
    /// <param name="splitestr"></param>
    /// <returns></returns>
    public static string ArrayToString<T>(T[] tarray, string splitestr)
    {
        string arrayString = "";
        for(int i = 0;i<tarray.Length;i++)
        {
            //bool?第一个值:第二个值
            arrayString += tarray[i] + ((i == tarray.Length - 1) ? "" : splitestr);
        }
        return arrayString;
    }

将字符串转化为字节数组

/// <summary>
    /// 将一个字符串转换为一个字节数组
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static byte[] StringToByteArray(string msg)
    {
        return System.Text.Encoding.UTF8.GetBytes(msg);
    }

将byte数组转换为字符串

/// <summary>
    /// byte数组转换为字符串
    /// </summary>
    /// <param name="byteArray"></param>
    /// <returns></returns>
    public static string ByteArrayToString(byte[] byteArray, int index, int size)
    {
        return System.Text.Encoding.UTF8.GetString(byteArray, index ,size);
    }

将字符串根据指定分隔符拆分,然后转化为Int数组

 public static int[] SpliteStringToIntArray(string str, char splitechar = ',')
    {
        //拆分
        string[] strArray = SpliteStringByChar(str, splitechar);
        //定义一个int数组
        int[] intArray = new int[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
        {
            intArray[i] = int.Parse(strArray[i]);
        }
        return intArray;
    }
    /// <summary>
    /// 根据特定的字符拆分字符串
    /// </summary>
    /// <param name="targetstr">被拆分字符串</param>
    /// <param name="splitechar">拆分符</param>
    /// <returns></returns>
    public static string[] SpliteStringByChar(string targetstr, char splitechar = ',')
    {
        return targetstr.Split(splitechar);
    }

将字符串根据指定分隔符拆分,然后转化为任意数组

public static T[] SpliteStringToArray<T>(string str, char splitechar = ',')
    {
        //拆分
        string[] strArray = SpliteStringByChar(str, splitechar);
        T[] tArray = new T[strArray.Length];
        for(int i = 0;i<strArray.Length;i++)
        {
            tArray[i] = (T)System.Convert.ChangeType(strArray[i], typeof(T));
        }
        return tArray;
    }
    /// <summary>
    /// 根据特定的字符拆分字符串
    /// </summary>
    /// <param name="targetstr">被拆分字符串</param>
    /// <param name="splitechar">拆分符</param>
    /// <returns></returns>
    public static string[] SpliteStringByChar(string targetstr, char splitechar = ',')
    {
        return targetstr.Split(splitechar);
    }

将字符串根据指定分隔符拆分,然后转化为float数组

public static float[] SpliteStringTofloatArray(string str, char splitechar = ',')
    {
        //拆分
        string[] strArray = SpliteStringByChar(str, splitechar);
        //定义一个int数组
        float[] intArray = new float[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
        {
            intArray[i] = float.Parse(strArray[i]);
        }
        return intArray;
    }
    /// <summary>
    /// 根据特定的字符拆分字符串
    /// </summary>
    /// <param name="targetstr">被拆分字符串</param>
    /// <param name="splitechar">拆分符</param>
    /// <returns></returns>
    public static string[] SpliteStringByChar(string targetstr, char splitechar = ',')
    {
        return targetstr.Split(splitechar);
    }

把任意对象转成Json

/// <summary>
   /// 把一个任意的对象转换为json的byte数组
   /// </summary>
   /// <param name="target"></param>
   /// <returns></returns>
    public static byte[] ObjectToJsonBytes(object target)
    {
        string json = LitJson.JsonMapper.ToJson(target);
        return StringToByteArray(json);
    }
    /// <summary>
    /// 将一个字符串转换为一个字节数组
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static byte[] StringToByteArray(string msg)
    {
        return System.Text.Encoding.UTF8.GetBytes(msg);
    }

使用正则表达式 将unicode转换为中文

/// <summary>
    /// 正则表达式:Unicode转换中文
    /// </summary>
    /// <param name="unicode"></param>
    /// <returns></returns>
    public static string UnicodeToString(string unicode)
    {
        Regex regex = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        return regex.Replace(unicode,
            delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
    }

2-3、对对象的处理

根据预制体和父物体,克隆对象,然后返回这个克隆的对象

/// <summary>
    /// 克隆并指定父物体
    /// </summary>
    /// <param name="prefab"></param>
    /// <param name="parent"></param>
    /// <returns></returns>
    public static GameObject Instantiate(GameObject prefab,GameObject parent)
    {
        GameObject gb = GameObject.Instantiate(prefab);
        gb.transform.parent = parent.transform;
        gb.transform.localPosition = gb.transform.localEulerAngles = Vector3.zero;
        gb.transform.localScale = Vector3.one;
        return gb;
    }

根据父物体,删除这个物体下的所有子物体

/// <summary>
    /// 删除指定物体下的所有子物体
    /// </summary>
    /// <param name="parent"></param>
    public static void DestroyChildGameObject(GameObject parent)
    {
        for(int i = 0;i<parent.transform.childCount;i++)
        {
            GameObject.Destroy(parent.transform.GetChild(i).gameObject);
        }
    }

2-4、对文件的处理

写入Json文件

/// <summary>
    /// 写入JSON文件
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="name">文件名</param>
    /// <param name="info">信息</param>
    public static void WriteJson(string path, string name, string info)
    {
        StreamWriter streamWriter;                               //声明一个流写入对象
        FileInfo fileInfo = new FileInfo(path + "/" + name); //文件 写到哪里:叫什么
        streamWriter = fileInfo.CreateText();           //打开文件往里写文本
        streamWriter.WriteLine(info);                            //写入信息 fileInfo streamWriter
        streamWriter.Close();
        streamWriter.Dispose(); //双关,写完
    }

读取Json文件

/// <summary>
    /// 读取JSON文件
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="name">文件名</param>
    /// <returns>string </returns>
    public static string ReadJson(string path, string name)
    {
        StreamReader streamReader;                               //声明一个流读取对象
        FileInfo fileInfo = new FileInfo(path + "/" + name); //文件 文件路径信息:叫什么
        streamReader = fileInfo.OpenText();             //打开文件往里写文本
        string info = streamReader.ReadToEnd();        //读信息 streamReader 给 info
        streamReader.Close();
        streamReader.Dispose(); //双关,写完
        return info;
    }

判断文件是否存在

/// <summary>
    /// 文件是否存在
    /// </summary>
    /// <param name="filename">文件名</param>
    public static bool IsExists(string filename)
    {
        bool isExists;                                                                 //声明一个布尔值,默认为false
        FileInfo fileInfo = new FileInfo(Application.persistentDataPath + "/" + filename); //判断路径
        //DirectoryInfo myDirectoryInfo=new DirectoryInfo(fileInfo.ToString()); //目录
        if (fileInfo.Exists == false) //路径不存在
        {
            isExists = false;
        }
        else
        {
            isExists = true;
        }
        return isExists; //返回bool值给函数 IsExist
    }

2-5、 其他

返回一个随机颜色

/// <summary>
    /// 随机颜色
    /// </summary>
    /// <returns> Color </returns>
    public Color RandomColor()
    {
        float r = UnityEngine.Random.Range(0f, 1f);
        float g = UnityEngine.Random.Range(0f, 1f);
        float b = UnityEngine.Random.Range(0f, 1f);
        Color color = new Color(r, g, b);
        return color;
    }

安卓平台显示信息

#if UNITY_ANDROID
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="text">Text.</param>
    /// <param name="activity">Activity.</param>
    public static void ShowToast(string text, AndroidJavaObject activity = null)
    {
        Debug.Log(text);
        if (activity == null)
        {
            AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            activity                     = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        }

        AndroidJavaClass  Toast   = new AndroidJavaClass("android.widget.Toast");
        AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
        activity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
            {
                AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", text);
                Toast.CallStatic<AndroidJavaObject>("makeText", context, javaString,
                    Toast.GetStatic<int>("LENGTH_SHORT")).Call("show");
            }
        ));
    }

    public static AndroidJavaObject ToJavaString(string CSharpString)
    {
        return new AndroidJavaObject("java.lang.String", CSharpString);
    }
#endif