I’ve built a MonoBehaviour that has a fields that are used to control the movement of the GameObject it is attached to.
I’m looking for a solution that allows my artists to come up with a bunch of pre-determined setups of this component. Storing that either as prefabs, or in some other library(?). Then a way to add that version of the component, into an existing GameObject from C# anywhere during game-play.
I’m reasonably new to Unity. To me, option 1 sounds terrible. Option 2 sounds like it’s not too complex, but it doesn’t seem right to me. I’m hoping there’s just some feature I haven’t come across yet.
Create a bunch of prefabs (“Mover A”, “Mover B”, “Mover C”), and store those in /Resources/. At play time, instantiate these prefabs, copy the component from the new instance into the existing one, destroy the new instance.
Change my MonoBehaviour so that it actually controls the movement of its own parent. Then instantiating the prefabs, adding them as children of the existing GameObject.
Should be pretty easy. You don’t even have to instantiate a prefab, as long as you have it stored in a variable you can access it’s scripts. The only thing you have to be very careful with is using the component data from the prefab to fill in those on the gameObject. You have to make sure that you copy all component values, and not just create references, because this might irreversibly change the values on your original prefab’s components. There are various ways of making “deep copies” of classes, here is one example.
public YourComponentType CopyYourComponentTypeValues(YourComponentType source) {
YourComponentType target = new YourComponentType();
FieldInfo[] sourceFields = source.GetType().GetFields(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
int i = 0;
for(i = 0; i < sourceFields.Length; i++) {
var value = sourceFields*.GetValue(source);*
_ sourceFields*.SetValue(target, value);_
_ }*_
* return target;* * }* Ther are also methoeds do it it in a more general way without having to pass and return specific types; This however goes beyond the scape of this post so I recommend checking over at StackOverflow or similar for such functions.
Although this looks like an Ad, the reason I made this is similar to you.
It’s artist friendly, copy and paste components just by drag and drop.
And there’s also a free version, use it with context menu.