Setting effect on model mesh causes Exception

I made terrain using vertices, normals and colour, and it looks just fine. I’m trying to make this a bit more universal; I’m trying to turn these vertices and indices into a model for easier drawing later. Here is my function to make a model:

    public static Model toModel(VertexBuffer vb, IndexBuffer ib, Effect effect, GraphicsDevice gd)
    {
        ModelMeshPart meshPart = new ModelMeshPart();
        meshPart.IndexBuffer = ib;
        meshPart.Effect = effect;
        meshPart.NumVertices = vb.VertexCount;
        meshPart.PrimitiveCount = vb.VertexCount / 3;
        meshPart.StartIndex = 0;
        meshPart.VertexBuffer = vb;
        meshPart.VertexOffset = 0;

        ModelMesh modelMesh = new ModelMesh(gd, new ModelMeshPart[] { meshPart }.ToList());

        Model returnval = new Model(gd, new List<ModelBone>(), new ModelMesh[] { modelMesh }.ToList());

        return returnval;
    }

And the call to it:

Tiles[x, y].TerrainModel = Utils.toModel(vertexBuffer, indexBuffer, new BasicEffect(this.GraphicsDevice), this.GraphicsDevice);

I don’t actually create a new effect for each one, I use a static one for all of my terrain models that I generate. I get an exception when I try to set meshPart.Effect saying (In exact words…) “System.NullReferenceException: 'Object reference not set to an instance of an object.'”. The static effect is initialized like so: = new BasicEffect(this.GraphicsDevice) and in the debugger, the effect is set afterwards and null beforehand. Also, my function isn’t receiving null either.

    ModelMeshPart meshPart = new ModelMeshPart();
    meshPart.IndexBuffer = ib;
    //meshPart.Effect = effect;
    meshPart.NumVertices = vb.VertexCount;
    meshPart.PrimitiveCount = vb.VertexCount / 3;
    meshPart.StartIndex = 0;
    meshPart.VertexBuffer = vb;
    meshPart.VertexOffset = 0;

    ModelMesh modelMesh = new ModelMesh(gd, new ModelMeshPart[] { meshPart }.ToList());
    ///
    meshPart.Effect = effect;//<<<
1 Like

Thanks, but sadly it doesn’t draw. :disappointed:

'kay…

public static Model toModel(VertexBuffer vb, IndexBuffer ib, Effect effect, GraphicsDevice gd)
{
    ModelMeshPart meshPart = new ModelMeshPart();
    meshPart.IndexBuffer = ib;
    //meshPart.Effect = effect;//>>1
    meshPart.NumVertices = vb.VertexCount;
    //meshPart.PrimitiveCount = vb.VertexCount / 3;
    meshPart.PrimitiveCount = ib.IndexCount / 3;
    meshPart.StartIndex = 0;
    meshPart.VertexBuffer = vb;
    meshPart.VertexOffset = 0;

    ModelMesh modelMesh = new ModelMesh(gd, new ModelMeshPart[] { meshPart }.ToList());
    meshPart.Effect = effect;//1

    List<ModelBone> bones = new List<ModelBone>();
    bones.Add(new ModelBone() { Transform = Matrix.Identity});//
    modelMesh.ParentBone = bones[0];

    Model returnval = new Model(gd, bones, new ModelMesh[] { modelMesh }.ToList());

    return returnval;
}