Why can you Add an instance of a component?

How come there is no way to set a GameObject component to an instantiated instance of a component? This ought to be supported.

This doesn’t work:
//load saved instance of Rotation script
Rotation rot = ES2.Load(savefilePath + “?tag=rotation” + tag);

//Add rotation component to prefab:
Rotation newRot=newPrefab.AddComponent();

//Replace added Rotation script with loaded instance:
newRot = rot;

The code compiles and runs without errors, but doesn’t actually work. The “newRot=rot” seems to do nothing.

The workaround is to manually set all the fields in the newly instantiated script to the values stored in the loaded instance. I’ve done this and it works fine. But doing this makes me want to break things, because it just seems so stupid.

It seems like you could write some utility method that uses reflection to automatically set all the fields, but I’m far to lazy to do this.

What gives Unity? :slight_smile:

Well this line does not replace the instance in the “newPrefab” of course as it only reassigns your local variable.

newRot = rot

That said… I could not find an easy way to do this.

At least internally there is a way (probably using some sort of reflection as well) as you can copy/paste components from one gameobject to another.