【问题标题】:add one gameobject component into another gameobject with values at runtime在运行时将一个游戏对象组件添加到另一个具有值的游戏对象中
【发布时间】:2021-08-24 17:19:06
【问题描述】:

在运行时我想将一个游戏对象组件复制到另一个游戏对象

在我的情况下,我有一台相机,其中添加了多个带有值设置的脚本。

我想在运行时添加到另一台相机中的相同组件。到目前为止,我已经尝试过,获取对象的所有组件然后尝试添加,但它不起作用。

Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for(var i = 0; i < components.Length; i++)
{
   objCamera.AddComponent<components[i]>();
   ///error in above line said adds a component class named/calss name to the gameobject                    
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我建议您设计您的应用,以便您可以致电 Instantiate 并获得克隆。比您想要的更容易和更快。
    但是,如果您坚持,您可以在 Unity 论坛上使用来自 this answer 的代码。

    您得到错误的原因是,您尝试将相同的组件(而不是它的副本)添加到另一个对象,即您想强制组件同时具有两个父对象,这是不可能的(也不可能从原始父对象“撕下”并移交给新对象;对于“模拟”这种效果,您还应该使用我链接的代码(或类似代码)。

    【讨论】:

    • 我想将一个游戏对象组件添加到另一个游戏对象中,即我使用上面的代码。
    • 那么你应该从我链接的答案(由 Shaffe 给出)中复制粘贴代码。在您的第二条评论中:您克隆了 GO,什么不起作用?您上面的代码将永远无法工作(我解释了原因)。但是,通过克隆,新对象将具有与旧对象相同的组件。
    • 嘿,马克我尝试了 shaffe 代码,但它没有保存/维护值,而是克隆新对象
    【解决方案2】:

    从 Mark 的回答中,我发现了这一点,它按预期工作,并且确实复制了字段值。这是完整的代码:

    //Might not work on iOS.
    public static T GetCopyOf<T>(this Component comp, T other) where T : Component
    {
        Type type = comp.GetType();
        if (type != other.GetType()) return null; // type mis-match
        BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
        PropertyInfo[] pinfos = type.GetProperties(flags);
        foreach (var pinfo in pinfos)
        {
            if (pinfo.CanWrite)
            {
                try
                {
                    pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
                }
                catch { } // In case of NotImplementedException being thrown.
            }
        }
        FieldInfo[] finfos = type.GetFields(flags);
        foreach (var finfo in finfos)
        {
            finfo.SetValue(comp, finfo.GetValue(other));
        }
        return comp as T;
    }
    public static T AddComponent<T>(this GameObject go, T toAdd) where T : Component
    {
        return go.AddComponent<T>().GetCopyOf(toAdd) as T;
    }//Example usage  Health myHealth = gameObject.AddComponent<Health>(enemy.health);
    

    【讨论】:

    • 他会尝试复制粘贴,然后零努力地返回“这不起作用”。你只是在浪费时间。但是感谢您的支持。
    • 我知道我以前曾试图帮助他。嘿,赞成是为了引导我使用这种不错的扩展方法。我不需要它,但它在工具类中;)
    • 哈哈,现在正在做同样的事情 :D 干杯伙伴! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多