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

后端 未结 8 880
执念已碎
执念已碎 2020-12-11 15:29

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.

8条回答
  •  不思量自难忘°
    2020-12-11 15:54

    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 shapes = new List();
    
        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.

提交回复
热议问题