Home > Software design >  Cloning objects in a way for all to behave the same
Cloning objects in a way for all to behave the same

Time:09-22

Is it possible to Instantiate a Prefab in Unity in a way that all the cloned objects behave the same?

for instance, if i rotate one, all the copies must rotate the same, if i change the color all must get the same color

I do know how to iterate on a array and apply the actions to each one of them but i was wondering if there is a simpler or more automated way

Thanks!!

CodePudding user response:

As you mentioned, a good way to achieve what you are trying to is to use a manager to handle the logic, then send the responding action to all objects that it is managing. If you would rather not use a manager, you can have some original instance of your object that handles the movement, rotation, scaling, etc. logic and child all other clones.

All childed clones of your original object will move, rotate and scale whenever the original object changes. The one caveat is that the clones when instantiated will be relative position, rotation, and scale to the parent object. You can assure the rotations are the same by instantiating the object with a rotation of Quaternion.Identity. A similar approach can be taken for the scale and position if you would like. As for the color, simply set a material and edit the sharedmaterial which would set the color of all instances of the object to whatever you set.

I do not believe there is a built-in way for all of these changes to apply to all clones. It would be cleaner to implement a manager that keeps a structure to hold and update each clone. If all you want the clones to mimic are the transform data and color, it can be done how I have mentioned. However, not everything can be updated this way so you are restricted in what you can do without a manager.

  • Related