Alter template mesh and have all instances update at runtime

I’m developing a 3D application that will read sets of mesh data at runtime and make many copies of it on the fly. The other component to this is to be able to modify the mesh data and propagate those changes to each copied instance while the program runs (e.g., load a new mesh, change colour, size, etc.).

The suggestion I was provided and got working looked something like this. To create my “base” template object (essentially a prefab):

GameObject baseObject = new GameObject("myBaseMesh");
MeshFilter meshfilter = baseObject.AddComponent<MeshFilter>();
MeshRenderer meshrenderer = baseObject.AddComponent<MeshRenderer>();
Mesh baseMesh = meshfilter.mesh;
baseMesh.vertices = ReadVertices(); //custom code
baseMesh.uv = ReadUVCoordinates(); //custom code
baseMesh.triangles = ReadFaces(); //custom code

Then to create each copy of it:

GameObject newInstance = (GameObject)Instantiate(baseObject, new Vector3(x, y, z), rotation);

This is working great, but when I alter the original baseObject, I would hope that its changes would propagate to each of the copies. Instead, only the base object updated and the copies kept their old state. I’m guessing Instantiate makes a one-to-one clone rather than referencing the old data, that’s fine and makes sense. Now I did find an alteration to it that works:

GameObject newInstance = (GameObject)Instantiate(baseObject, new Vector3(x, y, z), rotation);
newInstance.GetComponent<MeshFilter>().mesh = baseMesh;

So I instantiate it the same way, but I keep the Mesh data around and simply assign the same one to each copy. Now when I alter the baseMesh object, it naturally propagates to every copy. My big questions/concerns are:

  1. For each copy, it first creates a clone of all the mesh data, then immediately overwrites it by changing its mesh reference. Are there any performance/memory issues with this?

  2. I also have to share the other resources, in particular the colliders I’m using. But the collider is read-only, setup by the AddComponent method. Is it possible I can share the collider in some way, or would I simply have to go manually through each instance and manually update the collider’s properties (e.g., size, center) to match the baseObject’s? For example, like this:

BoxCollider baseObjectCollider = (BoxCollider)baseObject.collider;
foreach(GameObject instance in myInstanceList)
{
    BoxCollider instanceCollider = (BoxCollider)instance.collider;
    instanceCollider.size = baseObjectCollider.size;
    instanceCollider.center = baseObjectCollider.center;
}
  1. Is there a better way for Unity to maintain all these relationships at runtime?

Thanks for your time and input. :slight_smile:

I hate doing this but bump