反射使用
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Reflection; using System; public class ExampleCS : MonoBehaviour { public class MagicClass { private int magicBaseValue; public MagicClass() { magicBaseValue = 9; Debug.Log("MagicClass"); } public int ItsMagic(int preMagic) { Debug.Log("ItsMagic"); return preMagic * magicBaseValue; } } // Use this for initialization void Start () { TestMethod(); } [ContextMenu("TestMethod")] void TestMethod() { Type magicType = typeof(MagicClass); ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes); object magicClassObject = magicConstructor.Invoke(new object[] { }); MethodInfo magicMethod = magicType.GetMethod("ItsMagic"); object magicValue = magicMethod.Invoke(magicClassObject, new object[] { 100 }); ExampleCS exm = GetComponent<ExampleCS>(); Type exmapleCS = exm.GetType(); MethodInfo testMethod = exmapleCS.GetMethod("Test", BindingFlags.NonPublic | BindingFlags.Instance); testMethod.Invoke(exm, null); ExampleCS c = GetComponent<ExampleCS>(); c.GetType().InvokeMember("Test", BindingFlags.InvokeMethod|BindingFlags.NonPublic, null, c, new object[] { }); } void Test() { Debug.Log("Test==========="); } }
参考自:微软官网