c#教程 https://www.jxasp.com/blog
https://www.jxasp.com/blog
 
这篇文章主要介绍了Unity 通过反射给gameObject添加组件的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
 
 
C#版本
 
| 1 2 3 4 5 6 7 8 9 | publicstaticComponent AddComponent(GameObject go, stringassembly, stringclassname)
 {
     var asmb = System.Reflection.Assembly.Load(assembly);
     var t = asmb.GetType(assembly + "."+ classname);
     if(null!= t)
         returngo.AddComponent(t);
     else
         returnnull;
 }
 | 
lua版本
 
| 1 2 3 4 5 6 7 8 9 | function AddComponent(go, classname)
     local com = go:GetComponent(classname)
     if com then return com end
     local t = System.Type.GetType(classname)
     if t then
         return go:AddComponent(t)
     end
     return nil
 end
 | 
补充:添加组件和删除组件代码unity
 
代码添加组件
 
| 1 | gameObject.AddComponent ("FoobarScript");//最好使用类型方式,提交效率如typeof(Rigidbody)
 | 
注意没有RemoveComponent()方法。如果你想去掉一个组件,可以使用Object.Destroy。
 
添加组件和删除组件代码
 
| 1 2 3 4 5 | IEnumerator   Start () {
     this.gameObject.AddComponent(typeof(Rigidbody));  
     yieldreturnnewWaitForSeconds(0.5F);  
     Destroy(this.rigidbody);
   }
 | 
以上为个人经验,希望能给大家一个参考