将一个gameobject组件添加到另一个游戏对象中,其值在运行时

时间:2016-06-28 07:30:01

标签: c# unity3d

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

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

我想在运行时添加到另一台相机中的相同组件。到目前为止,我已经尝试了这个,获取对象的所有组件然后尝试添加,但它无法正常工作。

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                    
}

2 个答案:

答案 0 :(得分:2)

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

你得到错误的原因是,你尝试添加相同的组件(而不是副本)对于另一个对象,即你想强迫Component同时拥有两个父母,并且这是不可能的(它也不可能&#34;将其撕掉&#34) ;从原始父母移交到新父母;为了模拟这种效果,您还应该使用代码 - 或类似 - 我链接的。)

答案 1 :(得分:1)

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