Sharing a generated mesh between multiple game objects

So I have a component script, "GeneratedMesh", which I am attaching to a prefab. Basically, I would like every instance of a prefab to use the same generated mesh, but as I have it right now, the mesh is regenerated for every instance. So it looks something like this right now:

MyPrefabA has GeneratedMesh script

MyPrefabB has GeneratedMesh script

Instantiate MyPrefabA, MyPrefabA, MyPrefabB, MyPrefabB.

What happens:

GeneratedMesh generates 4 times, once for each instance.

What I would like to happen:

GeneratedMesh generates a mesh for MyPrefabA, then the second time it realizes MyPrefabA already has a mesh generated, and reuses it for the second instance. Then it generates a mesh for the first instance of MyPrefabB, then for the second MyPrefabB, it realizes there is already a mesh generated and uses that.

In the end, it only generates 2 times.


Leads I have so far:

I notice that MeshFilter has a 'sharedMesh' property. Presumably if I set the sharedMesh of the second instance to be the same as the first, Unity will consider them identical geometry and handle batching and all that.

So what I really need are suggestions for determining which prefab a mesh was generated for (really, it's all based on the parameters of the GeneratedMesh script on the prefab, as well as the material on the prefab), and then using that to coordinate sharing the mesh between instances...

Any thoughts?

Could you put the mesh generator on a different object, of which there is only one, so your script runs once. Then when you instantiate more objects, Find (or keep a reference to) that first object, then assign it's mesh out of there?

It's tough to tell, without code. But it's sounds like you're onto the solution. If you keep a reference to a mesh you created, then you can assign that to as many MeshFilter.mesh-es or MeshFilter.sharedMesh-es as you want, and the result will be the same: each MeshFilter will use the same (instanced one time only) mesh. However, if you ever get a mesh reference using a MeshFilter.mesh, then that mesh will be instanced.

Also, be aware that MeshFilter.mesh is only designed for runtime use; MeshFilter.sharedMesh is what you need to use in the Editor. This is a nice indicator of good practice: if your mesh generation scripting doesn't require multiple instances, run your code in the Editor. If you don't see errors, you're probably making nice, efficient code for runtime use.