Reputation: 9148
Ok,
I have a matrix of enemies Enemy enemyGrid[x, y]
Then, in my code I get an instance of one of the enemies by calling Enemy tmp = enemyGrid[a, b]
But if I change a property in tmp it is not reflected the next time I load the object from the matrix into the the same object tmp.
Each time I am finished with tmp I need to make it = null
to have the change reflected into the object in the gird?
Why is that? I thought that tmp would just hold a reference to the object and changes would be made directly in the main object.
Thanks.
CODE UPDATE:
Populating the grid:
Enemy [,] spriteGrid = new Enemy[countCols, countRows];
spriteGrid[x, y] = new Enemy();
Access an object and change properties:
Enemy tmp = spriteGrid[i, j];
tmp.canShoot = true;
tmp.Update(gameTime, game.Window.ClientBounds);
tmp.canShoot = false;
The last line (canShoot = false) does not reflect into the object stored in the grid.
Upvotes: 0
Views: 96
Reputation: 150178
The line
Enemy tmp = enemyGrid[a, b]
does not create a copy of the object in your matrix. It creates an alias to the same object instance. Changes to tmp do affect the instance in the grid that they alias.
Please post a short, complete code snippet that demonstrates the issue you are experiencing.
UPDATE
In your sample, you set
tmp.canShoot = true;
but then
tmpEnemy.canShoot = false;
Two different variables.
Update 2
@Amry's comment is also accurate... if Enemy is a struct instead of a class, you would see this very behavior. That is because struct is a value type, meaning the assignment does create a copy rather than an alias.
Except for very special cases, you should never use a struct that is mutable (that is, a struct whose value can change after it is initially created).
Upvotes: 3