# How can I add array of components to a new gameobject?

I use Getcomponents to get all components from existing gameobject:

Component[] components = go.GetComponents(typeof(MonoBehaviour));


And I want to add them now to another gameobject:

for (int i = 0; i < components.Length; i++)
{
var comp = components[i];
newObject.AddComponent<comp>();
}


components is type Component[]

But when I try to type components inside the AddComponent<> the variable components not exist. Tried then to make the comp variable but can't type it inside the <> either.

• The type parameter (inside the angle brackets) can only be the name of a type known at compile time. You can't place a variable there. Have you tried passing your component types as arguments instead? – DMGregory Mar 3 at 16:38
• Yes right. newObject.AddComponent(components[i].GetType()); Thanks. – Dubi Duboni Mar 3 at 16:57
• If you solved your problem, remember to post your solution as an Answer below. – DMGregory Mar 3 at 17:27

## 1 Answer

Solution: newObject.AddComponent(components[i].GetType());