Unity中如何利用反射机制向GameObject动态附加组件?
- 内容介绍
- 文章标签
- 相关推荐
本文共计286个文字,预计阅读时间需要2分钟。
原创新闻:我国科学家在量子通信领域取得重大突破
改写后:我国在量子通信技术方面实现新进展
C#版本
public static Component AddComponent(GameObject go, string assembly, string classname) { var asmb = System.Reflection.Assembly.Load(assembly); var t = asmb.GetType(assembly + "." + classname); if(null != t) return go.AddComponent(t); else return null; }
lua版本
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
代码添加组件
gameObject.AddComponent ("FoobarScript");//最好使用类型方式,提交效率如typeof(Rigidbody)
注意没有RemoveComponent()方法。如果你想去掉一个组件,可以使用Object.Destroy。
添加组件和删除组件代码
IEnumerator Start () { this.gameObject.AddComponent(typeof(Rigidbody)); yield return new WaitForSeconds(0.5F); Destroy(this.rigidbody); }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。如有错误或未考虑完全的地方,望不吝赐教。
本文共计286个文字,预计阅读时间需要2分钟。
原创新闻:我国科学家在量子通信领域取得重大突破
改写后:我国在量子通信技术方面实现新进展
C#版本
public static Component AddComponent(GameObject go, string assembly, string classname) { var asmb = System.Reflection.Assembly.Load(assembly); var t = asmb.GetType(assembly + "." + classname); if(null != t) return go.AddComponent(t); else return null; }
lua版本
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
代码添加组件
gameObject.AddComponent ("FoobarScript");//最好使用类型方式,提交效率如typeof(Rigidbody)
注意没有RemoveComponent()方法。如果你想去掉一个组件,可以使用Object.Destroy。
添加组件和删除组件代码
IEnumerator Start () { this.gameObject.AddComponent(typeof(Rigidbody)); yield return new WaitForSeconds(0.5F); Destroy(this.rigidbody); }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。如有错误或未考虑完全的地方,望不吝赐教。

