I'm not talking about the InstancedModel technique here.
I have a problem overriding my model's effects as per several good examples out there.
I have a class that contains my model data; this class has a .Load() method that loads the model from the content pipeline, storing it as a member variable, then overriding the effect with a custom effect for use later on in the Draw() method.
A have several instances of this class in an ArrayList and I call each of the Load() methods for the classes. This performs the following code:
| 1 |
public class ModelContainer |
| 2 |
{ |
| 3 |
Model model; |
| 4 |
|
| 5 |
public void Load(ContentManager content, string path) |
| 6 |
{ |
| 7 |
model = content.Load<Model>(path); |
| 8 |
|
| 9 |
//Some code here to load the custom effect, and set up my meshTextures Array. |
| 10 |
|
| 11 |
//Now to store the old texture and override the old Effect. |
| 12 |
int texIndex = 0; |
| 13 |
foreach (ModelMesh mesh in model.Meshes) |
| 14 |
{ |
| 15 |
foreach (ModelMeshPart meshPart in mesh.MeshParts) |
| 16 |
{ |
| 17 |
BasicEffect tmpBEffect = (BasicEffect)meshPart.Effect; |
| 18 |
meshTextures[texIndex] = tmpBEffect.Texture; |
| 19 |
meshPart.Effect = customEffect.Clone(graphics.GraphicsDevice); |
| 20 |
texIndex++; |
| 21 |
} |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
} |
The problem arises when the array contains two instances of the same model.
My loading the content from the content pipeline, it seems that the changes I make to the Effect object in each meshpart is somehow cached. The next time I load the model, the effect is already set (even though it's a new instance of my class) thus the code to cast Effect as BasicEffect crashes (you can't do this) - Line 17 above.
I know there's an obvious optimisation to not load the same model for every instance, but I want to understand this behaviour of Content.Load<T>() and if this a common problem to solve with a standard piece of game code.
Any suggestions here?