zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Unity3D日常开发】提供开发效率系列之工具类的建立

效率工具开发 系列 建立 提供 Unity3D 日常
2023-09-11 14:19:57 时间

推荐阅读

一、导言

在开发中,我们会将调用次数比较多的函数单独提出来写到一个类中,比如字符串转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

三、拓展方法

拓展方法的使用方法很简单,只需要新建一个类,将拓展方法写进去就行,不需要继承命名空间。

public static class MyExtensions
{
    //获取父物体下面的所有子对象 拓展于Transform 返回类型为List
    public static List<GameObject> GetChild(this Transform obj)
    {
        List<GameObject> tempArrayobj = new List<GameObject>();
        foreach (Transform child in obj)
        {
            tempArrayobj.Add(child.gameObject);
        }
        return tempArrayobj;
    }
    //获取父物体下面的所有子对象 拓展于GameObject 返回类型为List
    public static List<GameObject> GetChild2(this GameObject obj)
    {
        List<GameObject> tempArrayobj = new List<GameObject>();
        foreach (Transform child in obj.transform)
        {
            tempArrayobj.Add(child.gameObject);
        }
        return tempArrayobj;
    }
    //获取父物体下面的所有子对象 拓展于GameObject 返回类型为数组
    public static GameObject[] GetChild3(this GameObject obj)
    {
        List<GameObject> tempArrayobj = new List<GameObject>();
        foreach (Transform child in obj.transform)
        {
            tempArrayobj.Add(child.gameObject);
        }
        GameObject[] tempArraobj2 = tempArrayobj.ToArray();
        return tempArraobj2;
    }
    //将字符串强转为int类型 如果出错返回0
    public static int ToInt(this string s, int defaultValue = 0)
    {
        int i;
        return int.TryParse(s, out i) ? i : defaultValue;
    }
}

下面看一下怎么使用:

比如说获取所有子对象,可以这么写,正常写法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SplitAnomaly : MonoBehaviour
{
    private List<GameObject> m_Child;//所有子对象

    private void Start()
    {
        m_Child = GetChild(transform);//获取所有子对象
    }

    //获取所有子对象
    public List<GameObject> GetChild(Transform obj)
    {
        List<GameObject> tempArrayobj = new List<GameObject>();
        foreach (Transform child in obj)
        {
            tempArrayobj.Add(child.gameObject);
        }
        return tempArrayobj;
    }
}

用了拓展方法之后的写法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SplitAnomaly : MonoBehaviour
{
    private List<GameObject> m_Child;//所有子对象

    private void Start()
    {
        m_Child = m_Child.transform.GetChild();//获取所有子对象
    }
}
public static class MyExtensions
{
	//获取父物体下面的所有子对象 拓展于Transform 返回类型为List
    public static List<GameObject> GetChild(this Transform obj)
    {
        List<GameObject> tempArrayobj = new List<GameObject>();
        foreach (Transform child in obj)
        {
            tempArrayobj.Add(child.gameObject);
        }
        return tempArrayobj;
    }
}

就是在对象的transform组件再.出来一个函数:
在这里插入图片描述
更多拓展方法的用法可以百度。

四、后记


你的点赞就是对博主的支持,有问题记得留言:

博主主页有联系方式。

博主还有跟多宝藏文章等待你的发掘哦:

专栏方向简介
Unity3D开发小游戏小游戏开发教程分享一些使用Unity3D引擎开发的小游戏,分享一些制作小游戏的教程。
Unity3D从入门到进阶入门从自学Unity中获取灵感,总结从零开始学习Unity的路线,有C#和Unity的知识。
Unity3D之UGUIUGUIUnity的UI系统UGUI全解析,从UGUI的基础控件开始讲起,然后将UGUI的原理,UGUI的使用全面教学。
Unity3D之读取数据文件读取使用Unity3D读取txt文档、json文档、xml文档、csv文档、Excel文档。
Unity3D之数据集合数据集合数组集合:数组、List、字典、堆栈、链表等数据集合知识分享。
Unity3D之VR/AR(虚拟仿真)开发虚拟仿真总结博主工作常见的虚拟仿真需求进行案例讲解。
Unity3D之插件插件主要分享在Unity开发中用到的一些插件使用方法,插件介绍等
Unity3D之日常开发日常记录主要是博主日常开发中用到的,用到的方法技巧,开发思路,代码分享等
Unity3D之日常BUG日常记录记录在使用Unity3D编辑器开发项目过程中,遇到的BUG和坑,让后来人可以有些参考。