# How to load multiple 3D models dynamically xna

I want to load multiple 3D models .fbx at the same time in my map display.
I can load First Model but when I use ContentBuilder to Load another Model, I Got Error in effect.EnableDefaultLighting (); This my load function

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();

// Default to the directory which contains our content files.
string assemblyLocation = Assembly.GetExecutingAssembly().Location;
string relativePath = Path.Combine(assemblyLocation, "../../../../Content");
string contentPath = Path.GetFullPath(relativePath);
fileDialog.InitialDirectory = contentPath;
fileDialog.Filter = "Model Files (*.fbx;*.x)|*.fbx;*.x|" +
"FBX Files (*.fbx)|*.fbx|" +
"X Files (*.x)|*.x|" +
"All Files (*.*)|*.*";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
}
}
{
Cursor = Cursors.WaitCursor;
editorDesign1.Model = null;
// editorDesign1.CurrentModel.Model = null;
// Tell the ContentBuilder what to build.
contentBuilder.Clear();
// Build this new model data.
string buildError = contentBuilder.Build();
if (string.IsNullOrEmpty(buildError))
{
// If the build succeeded, use the ContentManager to
// load the temporary .xnb file that we just created.
}
else
{
// If the build failed, display an error message.
MessageBox.Show(buildError, "Error");
}

Cursor = Cursors.Arrow;
}


and this is my Draw model function

public void DrawModel()
{
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.World = Matrix.CreateTranslation(Position) * Matrix.CreateRotationX(Rotation.X) * Matrix.CreateScale(Scale) * Matrix.CreateRotationY(Rotation.Y) * Matrix.CreateRotationZ(Rotation.Z);

effect.View = view;
effect.Projection = projection;
}

mesh.Draw();
}
}


The problem is when I create two object from my model class and use ContentBuilder to Load another Model I get an exception AccessViolationException was Unhandled Attempted to read or write protected memory. This is often an indication that other memory is corrupt
and get another exception NullReferenceException was unhandled

Can anyone help me tho solve this problem?

I can find several problems, mainly with your workflow. First it looks like your editor can only show one model at a time anyway. Every time the dialog is launched the editor is cleared. You should use an array or a list to contain the models that are in the editor.

editorDesign1.Model = null;
...


Should become...

editorDesign1.Models = new List<Model>(); // or Models.Clear();
...

Your AccessViolationException is probably caused by the fact that when you build a model it saves it to the Model file. When you try to load another model, it also tries to write to the Model file which already exists and is protected, so the error is thrown.