I would like to do this (example below). This is just an example (I am not in my game using the constructor to create the MonoBehaviour/GameObject, I am instead storing the MonoBehaviour in a variable and then want to add it in its current state as a component to another game object).
// I have a MonoBehaviour component stored in a variable with some configuration on it var anim = new Animator(); // Example configuration anim.applyRootMotion = true; // I have a GameObject I want to add the MonoBehaviour component inside the variable to var obj = new GameObject(); // I want to add this pre-existing component to the object, rather than adding a new one with AddComponent<Animator>(). This code does not work (Compiler Error CS1503) obj.AddComponent(anim); // This below is NOT what I want (the Animator will not have the properties on it like the one the variable has) obj.AddComponent<Animator>();
I would appreciate it if anyone knows a solution that does this behaviour specifically, rather than a workaround. I am not able to use a prefab to instantiate the object that has a component with the desired pre-configured state set in the editor.
It needs to be done at runtime (the setting of the component variable and the adding of the component).
I did see this Adding components from prefab into existing GameObject - Questions & Answers - Unity Discussions but it’s based on a prefab, rather than runtime scripting. And I don’t really want to use reflection if at all possible.
If there is definitely no solution, then a workaround would be nice though :).