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

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.

Answer1:

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

Answer2:

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.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:how to clone several game objects in a way that clone properties of one can be adjusted to match all