Swapping Meshes

Hey, All,

How do I swap out the mesh component in a MeshFilter?

Say I have a MeshFilter which uses mesh “Cube”, but there is another mesh in the assets (but not currently used in the game) called “Sphere”, how do I swap them over?

A quick attempt I made was:

				((MeshFilter) GetComponent("MeshFilter")).mesh = GameObject.Find("Palm - polySurface1");

But this doesn’t work - Unity reports the following error:

error CS0029: Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Mesh'

But other than using GameObject.Find, I can’t really think of another way to do this…

Any ideas?

GameObject.Find, as the name (and documentation) suggests finds and returns only GameObjects, while you want a Mesh asset.

To get your Mesh asset, you should use Resources.Load :

Ah, OK - how fast is that load, though? I’m keen to make this swap essentially instantaneous - I don’t want to have to wait for a load?

Anyone have any idea about this? Is loading a resource instantaneous, or will I see delays in my models updating?

You would typically use Resources.Load in Start to load all meshes you will need and only swap references during the game.

However, using Resources.Load has the disadvantage that every scene in your game will contain these meshes (as Unity cannot know when you might decide to load them). If you have other scenes, it’s probably better to just give your script a number of mesh variables (or just an array) and drag all the meshes you need into these variables in the inspector.