文字列をクラスに変換し、Unityでメソッドを呼び出します



Convert String Class



Unityで最も一般的に使用されているプログラミング言語はC#です。現在、C#のリフレクションを使用して、文字列文字列をクラスに変換し、その中のメソッドを呼び出しています。
まず、UnityでC#スクリプトTest_StringToMethodを作成します。このスクリプトでは、テストクラスをランダムに作成しています。

public class Method { public void TestStringToMethod_1() { Debug.Log('The conversion is successful, method one is successfully called!') } public void TestStringToMethod_2(string str ,GameObject obj) { Debug.Log('The conversion is successful, method two is successfully called! Parameters:' + str) Debug.Log('The conversion is successful, method two is successfully called! Parameters:' + obj.name) } }

次。リフレクションテクノロジーを使用して、文字列がクラス名に変換され、メソッドが呼び出されます。
ここでは、名前空間を参照する必要があります



using System.Reflection//Reflected reference

最初にいくつかの変数を定義します

string className = 'Method'//Class name string methodName_1 = 'TestStringToMethod_1'//Method name to be called string methodName_2 = 'TestStringToMethod_2'//Method name to be called Type t

次に、変換を開始し、メソッドを呼び出します



void Start() { t = Type.GetType(className)//Get the class of the same name through the className of the string type var obj = t.Assembly.CreateInstance(className)//Create an instance of the obtained class //Call of a method without parameters MethodInfo method_1 = t.GetMethod(methodName_1)//Get the method with the same name through string type methodName method_1.Invoke(obj, null)//Call the method 'TestStringToMethod_1' in the t class instance obj, the second parameter has no additional fields and directly uses null //Call of method with parameters object[] parameters = new object[] { 'test' ,this.gameObject}//All parameters are thrown into the field where the method runs together, there can be multiple MethodInfo method_2 = t.GetMethod(methodName_2) method_2.Invoke(obj, parameters)//Call the method 'TestStringToMethod_2' in the t class instance obj }

全体的なコード
画像
次に、Unityで実行中の結果をいくつか見てみましょう
画像