2016-06-28 36 views
0

在運行時,我想將一個Gameobject組件複製到另一個gameobject在運行時將一個gameobject組件添加到另一個具有值的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

我建議設計你的應用程序,這樣你就可以調用Instantiate並獲得一個克隆。比你想要的更容易和更快。
但是,如果你堅持,你可以在Unity論壇上使用this answer的代碼。

你得到的錯誤的原因是,你嘗試添加相同的組件(而不是它的副本)到另一個對象,即你想迫使組件同時擁有兩個父母,那不是可能的(也不可能從原始父母「撕掉」並交給一個新的;爲了「模擬」這種效果,你還應該使用代碼 - 或類似的 - 我鏈接)。

+0

我想添加一個gameobject組件到另一個gameobject,即我使用上面的代碼。 –

+0

好吧,我做克隆,然後它仍然不工作 –

+0

然後,你應該複製粘貼從我鏈接的答案(由莎法給出)的代碼。至於你的第二條評論:你克隆了GO,哪些不起作用?上面的代碼永遠不會工作(我解釋了爲什麼)。然而,通過克隆,新對象將具有與舊對象相同的組件。 – 2016-06-28 08:22:48

1

從馬克的答案我發現這個,它的工作原理和預期一樣,它複製字段值。這裏是完整的代碼:

//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); 
+1

他會嘗試複製粘貼和零努力回來一個「這不行」。你只是浪費你的時間。但感謝upvote。 – 2016-06-28 08:49:53

+1

我知道我以前曾試圖幫助他。嘿,這個積極的態度是讓我引領這個漂亮的擴展方法。我不需要它,但它的工具類; –

+0

哈哈,現在做同樣的事情:D乾杯隊友! ;) – 2016-06-28 08:58:17

相關問題