"Why do others use Unity to write code so fast and so strong", "Because they use tools"

"Why do others use Unity to write code so fast and so strong", "Because they use tools"

Recommended reading

1. Introduction

In the development, we will separately propose the functions that are called more frequently and write them into a class, such as string conversion to hexadecimal, string encryption, these are more commonly used, and these commonly used functions can be extracted , Put in the tool class, convenient to call

2. Tools

2-1. Find objects

According to the parent object, find the child object with the specified name and return the GameObject object

//child is the parent node 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 the query to the sub-object 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 the query to the sub-object GameObject its = Find(child.transform.GetChild(i).gameObject, name); //If it is not empty, it means that there is a secondary object. Return the object if (its != null ) { return its.gameObject; } } return null ; } Copy code

According to the parent object, find the child object of the specified component with the specified name, and return the object of the specified component

//child is the parent node of the object to be queried, and name is the name of the child object to be queried. The return is a generic public static T Find < T >( GameObject child, string name ) { //Define a Transform variable it to receive the query to the sub-object 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 the query to the sub-object GameObject its = Find(child.transform.GetChild(i).gameObject, name); //If it is not empty, it means that there is a secondary object. Return the object if (its != null ) { return its.GetComponent<T>(); } } return default ; } Copy code

According to the name, return the component under the specified name

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

According to the name, return the specified Button component

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

2-2. Processing of text

Concatenate all characters in the array according to a specific separator

/// <summary> /// Convert an array into a string and splice it according to a specific separator /// </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? The first value: the second value arrayString += tarray[i] + ((i == tarray.Length- 1 )? "" : splitestr); } return arrayString; } Copy code

Convert string to byte array

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

Convert byte array to string

/// <summary> /// byte array is converted to string /// </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 code

Split the string according to the specified delimiter, and then convert it into 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 the string according to specific characters /// </summary> /// <param name="targetstr">The split string </param> /// <param name ="splitechar"> Split character </param> /// <returns> </returns> public static string [] SpliteStringByChar ( string targetstr, char splitechar = ',' ) { return targetstr.Split(splitechar); } Copy code

Split the string according to the specified delimiter, and then convert it into 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 the string according to specific characters /// </summary> /// <param name="targetstr">The split string </param> /// <param name ="splitechar"> Split character </param> /// <returns> </returns> public static string [] SpliteStringByChar ( string targetstr, char splitechar = ',' ) { return targetstr.Split(splitechar); } Copy code

Split the string according to the specified delimiter, and then convert it into 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 the string according to specific characters /// </summary> /// <param name="targetstr">The split string </param> /// <param name ="splitechar"> Split character </param> /// <returns> </returns> public static string [] SpliteStringByChar ( string targetstr, char splitechar = ',' ) { return targetstr.Split(splitechar); } Copy code

Convert any object into Json

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

Use regular expressions to convert unicode to Chinese

/// <summary> /// Regular expression: Unicode conversion to 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 code

2-3. Treatment of objects

According to the prefab and the parent object, clone the object, and then 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 code

According to the parent object, delete all child objects under this object

/// <summary> /// Delete 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 code

2-4. Handling of documents

Write Json file

/// <summary> /// Write JSON file /// </summary> /// <param name="path"> path </param> /// <param name="name"> file name </param> /// <param name="info"> </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 is the file written: what is it called streamWriter = fileInfo.CreateText(); //Open the file and write in it Text streamWriter.WriteLine(info); //Write information fileInfo streamWriter streamWriter.Close(); streamWriter.Dispose(); //Pun, finish writing } Copy code

Read Json file

/// <summary> /// Read JSON file /// </summary> /// <param name="path"> path </param> /// <param name="name"> file name </param> /// <returns> string </returns> public static string ReadJson ( string path, string name ) { StreamReader streamReader; //Declare a stream reading object FileInfo fileInfo = new FileInfo(path + "/" + name); //File file path information: what is it called streamReader = fileInfo.OpenText(); //Open the file and write in it Text string info = streamReader.ReadToEnd(); //Read information streamReader to info streamReader.Close(); streamReader.Dispose(); //Pun, finish writing return info; } Copy code

Determine whether the file exists

/// <summary> /// Does the file exist? /// </summary> /// <param name="filename"> file name </param> public static bool IsExists ( string filename ) { bool isExists; //Declare a boolean value, the default is false FileInfo fileInfo = new FileInfo(Application.persistentDataPath + "/" + filename); //Judgment 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 value to function IsExist } Copy code

2-5, 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 code

Android platform display 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); } # endifCopy code