I want to add a Component to a GameObject using an existing instance of the Component class.

Let's say I have the class Foo:

public class Foo : MonoBehaviour {
    int id {get; set;}
    string name {get; set;}
    //and other many variables

In another class I already have an instance of Foo with all variables setup.

What I want to do is attach the existing instance of Foo to a GameObject, instead to attach it and then setup all the variables.

Something like that, it is just an example, of course it give errors:

GameObject go;      //Existing GameObject
Foo foo;            //Existing instance of Foo with variables setup.  


Instead of doing:

GameObject go;      //Existing GameObject
Foo foo;            //Existing instance of Foo with variables setup.  


Foo myComponent = go.GetComponent<Foo>();
myComponent.id = foo.id;
myComponent.name = foo.name;
//and so on

Is there a way to do that?

  • \$\begingroup\$ Nah, there's no way of copying/duplicating variables from one Component to another Component via scripting that I know of. I think what you're doing with your current method is the way to go, setting the variables one by one. \$\endgroup\$ Apr 23 '14 at 22:37

I don't know of a way to add the existing component. However, it is possible to make it easier to duplicate the existing component into the new one:

Foo newFoo = go.AddComponent(foo.GetType());
foreach (FieldInfo fi in foo.GetType().GetFields())
  fi.SetValue(newFoo, fi.GetValue(foo));

This uses reflection to copy the fields of the old component to the fields of the new component. Do note that GetFields() only returns fields marked as public. You can get everything but private fields using binding flags.

Remember to update the reference at the end if you want to use foo to reference go's Foo component:

foo = newFoo;

Alternatively, I'm not sure how you're creating the foo component in the first place, but I'd pass in the game object you want to attach.

public static Foo CreateFoo(ref GameObject go) {
    Foo foo = go.AddComponent<Foo>();
    //Setup foo
    return foo;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .