how to clone several game objects in a way that clone properties of one can be adjusted to match all others in scene view


how to clone several game objects in a way that clone properties of one can be adjusted to match all others in scene view



I asked How can I adjust shape/dimensions of one clone to affect all other clones in the scene view and the accepted answer was spot on. It could only clone one game object. I tried making some adjustments but the only solution I came up with was adding duplicate methods for additional objects. This doesn't work well when dealing with several game objects to be cloned. How can I clone several game objects in a similar way so that adjusting the components and properties live of one clone is replicated on all the others scene view without having to write duplicate methods.





Would you mind posting code for what you've already come up with?
– Eliasar
2 days ago




2 Answers
2



You should use events. Unity3d tutorials has a good, simple explanation: https://unity3d.com/learn/tutorials/topics/scripting/events



It sounds like you have an object that has several clones. You want changing the shape or dimensions of any of those objects to affect the other ones?



For this to happen, each object needs to know about the other ones. You can do this decentralized (each object contains a reference to each other) or centralized (one object governs the rest).



The centralized approach is more simple so I'll give a simple example.


public class Shape
{
public int length;
}

public class ShapeCentral
{
public List<Shape> shapes = new List<Shape>();

public void CloneShape()
{
//instantiate new shape
shapes.Add(new Shape());
}

public void SetCloneLength(int l)
{
shapes.ForEach(x => x.length = l);
}
}



As you can see, one object can control all the clones at once. The trick is to not create clones using other methods or you will run into trouble.



If you want to tighten up your variable access (which I recommend, its a good exercise) you could use a publisher/subscriber pattern. In this, when a new clone is instantiated, it subscribes to the SetCloneLength method. When you want to change the length, the central class publishes that message and it is sent to all the subscribers.



The difference here is that in my example, the central class needs to keep track of all the clones, in publisher/subscriber, you don't.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift