Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Strange for loop behavior?

Discussion in 'Scripting' started by PharaohZeus, Aug 16, 2023.

  1. PharaohZeus

    PharaohZeus

    Joined:
    Oct 11, 2015
    Posts:
    3
    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:

    Code (CSharp):
    1. for (int i = indexToDelete; i < allPhotos.Count; i++)
    2. {
    3. Debug.Log($"allPhotos[{i}], {allPhotos[i].transform.position}");
    4. Debug.Log($"previousPositions[{i}], {previousPositions[i].position}");
    5. }

    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!

    Code (CSharp):
    1. for (int i = indexToDelete; i < allPhotos.Count; i++)
    2. {
    3. allPhotos[i].transform.position = previousPositions[i].position;
    4. allPhotos[i].transform.rotation = previousPositions[i].rotation;
    5. allPhotos[i].transform.localScale = previousPositions[i].localScale;
    6. Debug.Log($"allPhotos[{i}], {allPhotos[i].transform.position}");
    7. Debug.Log($"previousPositions[{i}], {previousPositions[i].position}");
    8. }
    9.  
     
    Last edited: Aug 16, 2023
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    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.
     
    PharaohZeus likes this.
  3. PharaohZeus

    PharaohZeus

    Joined:
    Oct 11, 2015
    Posts:
    3
    This was it. I never knew populating a list with transforms of gameobjects is a live reference - rookie mistake. Thank you!
     
    Bunny83 and Yoreki like this.
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    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! :)
     
    PharaohZeus and Bunny83 like this.