See the following code:
List<Vector2> axes = new List<Vector2>();
axes.Add(TopRight() - TopLeft());
axes.Add(BottomLeft() - TopLeft());
axes.Add(otherRectangle.TopRight() - otherRectangle.TopLeft());
axes.Add(otherRectangle.BottomLeft() - otherRectangle.TopLeft());
// Try normalizing vectors?
foreach (Vector2 axis in axes)
{
axis.Normalize();
}
the Vector2.Normalize() method is a void method that normalizes the vector it’s called on. Yet for some reason when I do this loop it doesn’t normalize the vectors. Am I just unable to modify a list this way?
Some oddities:
- Iterating with a for loop, i.e.
axis[i].Normalize()doesn’t work. - Iterating with the built-in
List<T>.ForEachiterator does not work. - Creating a normalizing the vector before adding it to the list rather than iterating over the list does work.
Why does iteration not work?
The
foreachloop creates a local copy of the sequence element. You only normalize the copy.You will need to do something like:
This unintuitive behavior demonstrates, once again, why instance methods that mutate a struct are a bad idea.