scott mansoori
scott mansoori

Reputation: 1

Changing textures on one instance of a 3D model

I have created an array of spherical models representing rooms.

Model[] roomModel = new Model[21];

In my LoadContent method:

for (int x = 0; x < 21; x++)
{
    roomModel[x] = Content.Load<Model>("Models\\sphere_model");
}

In my Draw method:

for (int x = 0; x < 21; x++)
{
    //copy any parent transforms
    Matrix[] transforms = new Matrix[roomModel[x].Bones.Count];
    roomModel[x].CopyAbsoluteBoneTransformsTo(transforms);                

    //draw the model; a model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in roomModel[x].Meshes)
    {
        //this is where the mesh orientation is set, as well as our camera and projection
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(modelRotation) * Matrix.CreateTranslation(modelPosition[x]);
            effect.View = Matrix.CreateLookAt(cameraPosition, new Vector3(0.0f,-100.0f,0.0f), Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(42.0f), aspectRatio, 1.0f, 10000.0f);                                                
        }
        mesh.Draw();
    }
}

I just want to change the texture on one of my spherical models, say roomModel[5]. When I use this code, it changes all of the room models.

foreach (ModelMesh mesh in roomModel[5].Meshes)
{   
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.Texture = textureToSet;                    
    }
}  

How do I make it change the texture of just one of the roomModels as opposed to all of them? All I can think of doing is creating an individual model for each room, but that sounds expensive.

Upvotes: 0

Views: 164

Answers (1)

pinckerman
pinckerman

Reputation: 4213

I think it's due to the Content Manager's behaviour:

Each instance of ContentManager will only load any given resource once. The second time you ask for a resource, it will return the same instance that it returned last time.

So, when you set

roomModel[x] = Content.Load<Model>("Models\\sphere_model");

you are giving the same reference to every model.

I think that's why your last code changes all your models.

Upvotes: 1

Related Questions