Recommended reading

  • CSDN home page
  • GitHub open source address
  • Unity3D plugin sharing
  • Jane’s address book
  • My personal blog
  • QQ group: 1040082875
  • CSDN Blog Star Poll (please vote for this article if it helps you)

One, the introduction

In the development, we will be called more times of the function separately put into a class, such as string to hexadecimal, to encrypt the string these are more commonly used, you can extract these commonly used functions, into the tool class, easy to call

Second, tools

2-1. Find an object

Based on the parent object, find the child object with the specified name and return the GameObject

// Child is the parent of the object to be queried, and name is the name of the child object to be queried
    public static GameObject Find(GameObject child, string name)
    {
        // Define a Transform variable it to receive queries to subobjects
        Transform it = child.transform.Find(name);
        if(it ! =null)
        {
            return it.gameObject;
        }
        if (child.transform.childCount == 0)
        {
            return null;
        }
        // Find the child object of the child object
        for (int i = 0; i < child.transform.childCount; i++)
        {
            // Recursive query defines a Transform variable its to receive queries to subobjects
            GameObject its = Find(child.transform.GetChild(i).gameObject, name);
            // If it is not empty, the subobject is returned
            if(its ! =null)
            {
                returnits.gameObject; }}return null;
    }
Copy the code

Finds the child object of the specified component with the specified name, based on the parent object. Returns the object of the specified component

// Child is the parent of the object to be queried, and name is the name of the child object to be queried
    public static T Find<T> (GameObject child, string name)
    {
        // Define a Transform variable it to receive queries to subobjects
        Transform it = child.transform.Find(name);
        if(it ! =null)
        {
            return it.GetComponent<T>();
        }
        if (child.transform.childCount == 0)
        {
            return default;
        }
        // Find the child object of the child object
        for (int i = 0; i < child.transform.childCount; i++)
        {
            // Recursive query defines a Transform variable its to receive queries to subobjects
            GameObject its = Find(child.transform.GetChild(i).gameObject, name);
            // If it is not empty, the subobject is returned
            if(its ! =null)
            {
                returnits.GetComponent<T>(); }}return default;
    }
Copy the code

Returns the component under the specified name, based on the name

/// <summary>
    ///Gets the T component of the object name
    /// </summary>
    /// <param name="namestring">The object of</param>
    /// <returns></returns>
    public static T FindT<T> (string namestring)
    {
        return GameObject.Find(namestring).GetComponent<T>();
    }
Copy the code

Returns the specified Button component by name

 /// <summary>
    ///Get Button component
    /// </summary>
    /// <param name="namestring"></param>
    /// <returns></returns>
    public static Button FindBtn(string namestring)
    {
        return GameObject.Find(namestring).GetComponent<Button>();
    }
Copy the code

2-2. Processing of text

Concatenates all characters in an array to a specific delimiter

/// <summary>
    ///Converts an array to a string, concatenated with a specific delimiter
    /// </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? First value: second value
            arrayString += tarray[i] + ((i == tarray.Length - 1)?"" : splitestr);
        }
        return arrayString;
    }
Copy the code

Converts a string to a byte array

/// <summary>
    ///Converts a string to a byte array
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static byte[] StringToByteArray(string msg)
    {
        return System.Text.Encoding.UTF8.GetBytes(msg);
    }
Copy the code

Convert the byte array to a string

/// <summary>
    ///Byte arrays are converted to strings
    /// </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);
    }
Copy the code

Splits a string according to the specified delimiter and converts it to an Int array

 public static int[] SpliteStringToIntArray(string str, char splitechar = ', ')
    {
        / / split
        string[] strArray = SpliteStringByChar(str, splitechar);
        // Define an int array
        int[] intArray = new int[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
        {
            intArray[i] = int.Parse(strArray[i]);
        }
        return intArray;
    }
    /// <summary>
    ///Split a string based on a specific character
    /// </summary>
    /// <param name="targetstr">Split string</param>
    /// <param name="splitechar">Split operator</param>
    /// <returns></returns>
    public static string[] SpliteStringByChar(string targetstr, char splitechar = ', ')
    {
        return targetstr.Split(splitechar);
    }
Copy the code

Splits a string according to the specified delimiter and converts it to an arbitrary array

public static T[] SpliteStringToArray<T> (string str, char splitechar = ', ')
    {
        / / split
        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>
    ///Split a string based on a specific character
    /// </summary>
    /// <param name="targetstr">Split string</param>
    /// <param name="splitechar">Split operator</param>
    /// <returns></returns>
    public static string[] SpliteStringByChar(string targetstr, char splitechar = ', ')
    {
        return targetstr.Split(splitechar);
    }
Copy the code

Splits the string according to the specified delimiter and converts it to a float array

public static float[] SpliteStringTofloatArray(string str, char splitechar = ', ')
    {
        / / split
        string[] strArray = SpliteStringByChar(str, splitechar);
        // Define an int array
        float[] intArray = new float[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
        {
            intArray[i] = float.Parse(strArray[i]);
        }
        return intArray;
    }
    /// <summary>
    ///Split a string based on a specific character
    /// </summary>
    /// <param name="targetstr">Split string</param>
    /// <param name="splitechar">Split operator</param>
    /// <returns></returns>
    public static string[] SpliteStringByChar(string targetstr, char splitechar = ', ')
    {
        return targetstr.Split(splitechar);
    }
Copy the code

Convert any object to Json

/// <summary>
   ///Converts an arbitrary object to a JSON byte array
   /// </summary>
   /// <param name="target"></param>
   /// <returns></returns>
    public static byte[] ObjectToJsonBytes(object target)
    {
        string json = LitJson.JsonMapper.ToJson(target);
        return StringToByteArray(json);
    }
    /// <summary>
    ///Converts a string to a byte array
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static byte[] StringToByteArray(string msg)
    {
        return System.Text.Encoding.UTF8.GetBytes(msg);
    }
Copy the code

Convert Unicode to Chinese using regular expressions

/// <summary>
    ///Regular expressions: Unicode conversion Chinese
    /// </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(); });
    }
Copy the code

2-3. Processing of objects

Clone object based on preform and parent object, and return the cloned object

/// <summary>
    ///Clone and specify the parent object
    /// </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;
    }
Copy the code

Delete all child objects under this object based on the parent object

/// <summary>
    ///Deletes all child objects under the specified object
    /// </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); }}Copy the code

2-4. Processing of documents

Write Json file

/// <summary>
    ///Write JSON file
    /// </summary>
    /// <param name="path">The path</param>
    /// <param name="name">The file name</param>
    /// <param name="info">information</param>
    public static void WriteJson(string path, string name, string info)
    {
        StreamWriter streamWriter;                               // Declare a stream write object
        FileInfo fileInfo = new FileInfo(path + "/" + name); // Where does the file go: what is it called
        streamWriter = fileInfo.CreateText();           // Open the file and write text inside
        streamWriter.WriteLine(info);                            // Write information fileInfo streamWriter
        streamWriter.Close();
        streamWriter.Dispose(); // This is a double entendre
    }
Copy the code

Reading Json files

/// <summary>
    ///Reading JSON files
    /// </summary>
    /// <param name="path">The path</param>
    /// <param name="name">The file name</param>
    /// <returns>string </returns>
    public static string ReadJson(string path, string name)
    {
        StreamReader streamReader;                               // Declare a stream read object
        FileInfo fileInfo = new FileInfo(path + "/" + name); // File file path information: what is it called
        streamReader = fileInfo.OpenText();             // Open the file and write text inside
        string info = streamReader.ReadToEnd();        StreamReader to info
        streamReader.Close();
        streamReader.Dispose(); // This is a double entendre
        return info;
    }
Copy the code

Check whether the file exists

/// <summary>
    ///Whether the file exists
    /// </summary>
    /// <param name="filename">The file name</param>
    public static bool IsExists(string filename)
    {
        bool isExists;                                                                 // Declare a Boolean value. Default is false
        FileInfo fileInfo = new FileInfo(Application.persistentDataPath + "/" + filename); // Determine the path
        //DirectoryInfo myDirectoryInfo=new DirectoryInfo(fileInfo.ToString()); / / directory
        if (fileInfo.Exists == false) // Path does not exist
        {
            isExists = false;
        }
        else
        {
            isExists = true;
        }
        return isExists; // Return bool to IsExist
    }
Copy the code

2-5, and other

Returns a random color

/// <summary>
    ///Random color
    /// </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;
    }
Copy the code

The Android platform displays information

#if UNITY_ANDROID
    /// <summary>
    ///Prompt information
    /// </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
Copy the code