当前位置:主页 > 软件编程 > .NET代码 >

Unity 如何通过反射给gameObject添加组件

时间:2021-08-17 07:34:06 | 栏目:.NET代码 | 点击:

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);
  }

您可能感兴趣的文章:

相关文章