下面的代码可以通过字符串创建实例,在一些特殊情况下,反射是很好的解决问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using UnityEngine; using System.Collections; using System.Reflection; public class Main : MonoBehaviour { void Start () { //获取包含当前执行的代码的程序集。 Assembly ass = Assembly.GetExecutingAssembly (); //使用区分大小写的搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。 Base o = ass.CreateInstance ("GameMain",true) as Base; o.writeString ("Start"); o = ass.CreateInstance ("Test",true) as Base; o.writeString("Start"); o = System.Activator.CreateInstance (o.GetType()) as Base; o.writeString ("Activator"); } } public class Base { public virtual void writeString(string value) { Debug.Log (value); } } public class GameMain : Base { public override void writeString (string value) { base.writeString ("this is GameMain : " + value); } } public class Test : Base { public override void writeString (string value) { base.writeString ("this is Test : " + value); } } |