In C#, there are two situations that might happen when you copy something, for example Vector2 position = positions[0];
:
- If the object is a struct, it will copy the entire object.
float
is a structure, int
is a structure, double
is a structure. Basically, this quote from msdn sums it well: Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy.
- If the object is a class, it will be passed around as a reference.
string
is a class and you usually make classes. When passed to a function or assigned to an object, modifying the copied object actually modifies the original object itself, since it is a reference.
What does this mean to us? Well, we have to be very careful when we pass variables around. When we pass a structure, we must know that it is not actually modified (unless we use keywords such as ref or out). When we pass a class, we must know that the original
object might be modified (although there are ways to clone a class).
Now, Vector2 is a structure. It implies that we can't iterate through it with a foreach loop (as you have tried) and that any copy will not modify the original object. So, when you do Vector2 ep1 = enemyPosition[0];
, you make a copy and only modify the copied version, so the objects won't move.
Instead, modify the objects directly, and I would recommend using a for-loop instead of doing it line-per-line. This will allow you to modify it later and add/remove objects without needing to modify your code. Do it like so (assuming that enemyPosition
is a List<Vector2>
):
for (int i = 0; i < enemyPosition.Count; ++i)
{
if (enemyPosition[i].X < 800)
{
enemyPosition[i].X--;
}
}
By using the loop, you remove code duplication, which makes it easier to later modify the program and fix bugs without forgetting a piece of your code. Always try to remove code duplication when you can, it will make your code more flexible.
In the same order of ideas, if we want to make it easier to change the program later on you might want to use constants rather than magic values. The 800
here requires the reader of the code to implicitly understand what it represents, therefore making it less readable and less flexible if you use this value somewhere else. I would advise against magic values. Instead, you could do the following:
// Somewhere in your class...
const int ScreenWidth = 800;
// In your Update method...
for (int i = 0; i < enemyPosition.Count; ++i)
{
if (enemyPosition[i].X < ScreenWidth)
{
enemyPosition[i].X--;
}
}
After that, you could change to a design with classes instead, which will probably make it all much cleaner. See Katana314's answer for doing so.