参考https://gameinstitute.qq.com/community/detail/122847
本身想做个通过字符串名字添加组件的功能,但是实现不了,参考了文章写了下面的代码
是通过MakeGenericMethod方法,将type转换为泛型参数,然后通过反射直接调用AddComponent
MethodInfo mi = typeof(GameObject).GetMethod(“AddComponent”).MakeGenericMethod(System.Type.GetType(str));
mi.Invoke(bufferobj, new object[] { “” });//参数第一个是调用这个方法的对象,第二个是方法参数。
但是实际上是实现不了的,因为AddComponent是重载过的,于是查找到了Component AddComponent(Type componentType);
所以
Type type = Type.GetType(str);
GameObject g = new GameObject();
g.AddComponent(type);
可以实现这个功能