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];

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.

  • \$\begingroup\$ 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? \$\endgroup\$ – DMGregory Mar 3 at 16:38
  • \$\begingroup\$ Yes right. newObject.AddComponent(components[i].GetType()); Thanks. \$\endgroup\$ – Dubi Duboni Mar 3 at 16:57
  • 1
    \$\begingroup\$ If you solved your problem, remember to post your solution as an Answer below. \$\endgroup\$ – DMGregory Mar 3 at 17:27

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.