Tariq
Tariq

Reputation: 593

Entire array's values being overwritten with each iteration in for loop

I have a for loop that iterates through an object array to set the values for the drawing of the object. Below is the code

for (int i = 0; i < screenBottom.Length; i++)
        {
            int newPostion = i * screenBottom[i].sourceRect.Width; 
            //go through sourceRect as we're using drawSimple mode
            screenBottom[i].sourceRect.X = newPostion; 
            screenBottom[i].Draw(spriteBatch);
        }

However each time a new value for sourceRect.X is set the value of sourceRect.X for ALL the objects in the array is overwritten. By the end of the for loop the value for all sourceRect.X's is equal to what only the last value should be. Through some testing I found this ONLY happens in a loop. If I change the values outside of a loop such an occurrence does not happen. Please help!

Upvotes: 1

Views: 1145

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062620

I suspect the array contains the same object lots of times, i.e. accidentally:

SomeType[] screenBottom = new SomeType[n];
for(int i = 0 ; i < screenBottom.Length ; i++)
    screenBottom[i] = theSameInstance;

You can check this simply with ReferenceEquals(screenBottom[0], screenBottom[1]) - if it returns true, this is the problem.

Note it could also be the case that all the array items are different, but that they all talk to the same sourceRect instance; you can check that with ReferenceEquals(screenBottom[0].sourceRect, screenBottom[1].sourceRect)

Upvotes: 9

Related Questions