# Why are changes in one object applied to all objects in a list?

I've got two List:

1. BasicModels: As Content has to be loaded at the start of the game I instanciate and load all models into this list.

2. ModelsOnScreen: Every time when a Model is added to the screen I take the corresponding object out of BasicModels and put it into ModelsOnScreen. At the same time I write the ID of the Model at it's location in ModelsOnScreen.

So the problem is though I change the Id at a specific place in the list, changes are applied to all models in ModelsOnScreen.

 for (int i = 0; i < _game.Models.Length; i++)
{
if (assetName == _game.Models[i].name.ToString())
{
_game.modelsOnScreen[_game.modelsOnScreen.Count - 1].ID = nameCounter;
}
}


What could be the problem? My theory is that the Models I put into ModelsOnScreen are only references, no separate instances. If that is so, how could I solve this problem?

greets BC++

• One note: content does not need be loaded at the start of the game. Each level could have its very own LoadContent, which you'd call when needed. You can even load content progressively, as the player walks out of areas and into new ones. Game.LoadContent is meant to load stuff for interfaces, maybe the first level and/or background art, icons or audio. – Elideb Feb 18 '12 at 16:20
• I tried to load content dynamically. The problem was, in order to do that I had to make my BasicModels DrawablegameComponents. As LoadContent is only called once. But only one Component of the same type can be added to the game. gamedev.stackexchange.com/questions/23224/… – チーズパン Feb 20 '12 at 8:47
• XNA's [Whatever]Components are not meant to be created in spades. They are supposed to be used for [Whatever]Manager/Engine: GraphicsEngine, PhysicsEngine, BulletManager, AIManager, PlayerManager... Except InputManager, since the order of Update calls is not guaranteed. – Elideb Feb 21 '12 at 15:48

Yes, your suspicion is correct — the .Add() method does not make a copy of the model, so when you change _game.modelsOnScreen[_game.modelsOnScreen.Count - 1] you are also changing _game.Models[i] — they refer to the same object. It's rare for a function to make a copy of an object.

If you want many different IDs associated with the same Model, then make a new class/struct that stores an ID and a model, and create a new instance of that for each ID.

• "the .Add() method does not make a copy of the model" Unless the model is a struct or any other value type. – Elideb Feb 21 '12 at 15:51

As far as I can tell, nameCounter is being assigned to the ID property of every single model added to modelOnScreen. Look closely at the loop and you'll see that your code is equivalent to:

for (int i = 0; i < _game.Models.Length; i++)
{
var model = _game.Models[i];
if (assetName == model.name.ToString())
{