我是靠谱客的博主 娇气小蝴蝶,这篇文章主要介绍Unity 如何通过反射给gameObject添加组件,现在分享给大家,希望可以做个参考。

C#版本

复制代码
1
2
3
4
5
6
7
8
9
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版本

复制代码
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)); yield return new WaitForSeconds(0.5F); Destroy(this.rigidbody); }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。如有错误或未考虑完全的地方,望不吝赐教。

最后

以上就是娇气小蝴蝶最近收集整理的关于Unity 如何通过反射给gameObject添加组件的全部内容,更多相关Unity内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(159)

评论列表共有 0 条评论

立即
投稿
返回
顶部