Strange for loop behavior?

I am working on a bit of code for a photo grid layout, and I am trying to handle photo reassignment of positions in a for loop after the user deletes a photo. I have tried everything, but I just don’t get it.

This logs the correct previousPositions I want to use:

for (int i = indexToDelete; i < allPhotos.Count; i++)
{
Debug.Log($"allPhotos[{i}], {allPhotos[i].transform.position}");
Debug.Log($"previousPositions[{i}], {previousPositions[i].position}");
}

once I put in the transform changes (of the allPhotos gameobjects), every previousPosition.position changes to previousPosition[indexToDelete]'s position. There is no outside code fiddling with these values, and when I only used the Debug.Log the values were correct. From my understanding, changing the transform values of the allPhotos gameobjects should not affect the transforms values of the previousPositions transforms. What am I overseeing? Thanks!

for (int i = indexToDelete; i < allPhotos.Count; i++)
{
allPhotos[i].transform.position = previousPositions[i].position;
allPhotos[i].transform.rotation = previousPositions[i].rotation;
allPhotos[i].transform.localScale = previousPositions[i].localScale;
Debug.Log($"allPhotos[{i}], {allPhotos[i].transform.position}");
Debug.Log($"previousPositions[{i}], {previousPositions[i].position}");
}

Try assigning new vectors instead of previousPosition[ i ].position/rotation/localScale, and see if that resolves your problem. Only thing i can think off right now is that you are somehow working with the same reference in both arrays.

This was it. I never knew populating a list with transforms of gameobjects is a live reference - rookie mistake. Thank you!

Yeah, Transforms are classes, thus reference types. It’s contents, mostly Vector3, are structs, thus value types. But if both arrays contain the same transforms, then depending on how you interact with them, you could overwrite both sides with such a loop.

Glad you resolved your issue! :slight_smile: