Search Unity

Array set to another Array

Discussion in 'Scripting' started by dcagemodels, Jul 14, 2022.

  1. dcagemodels

    dcagemodels

    Joined:
    Nov 26, 2018
    Posts:
    14
    Is there a more efficient way to do this? Without doing it manually?

    //adding images to the puzzle pieces
    puzzlePieces[0].sprite = Images[0];
    puzzlePieces[1].sprite = Images[1];
    puzzlePieces[2].sprite = Images[2];
    puzzlePieces[3].sprite = Images[3];
     
  2. julienkay

    julienkay

    Joined:
    Nov 12, 2013
    Posts:
    171
  3. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    Using a for loop. Iterate through to the length of one array.

    I don't think Copy would work, since in his example the arrays aren't the same type.
     
    Bunny83 and Kurt-Dekker like this.
  4. dcagemodels

    dcagemodels

    Joined:
    Nov 26, 2018
    Posts:
    14
    So like this?
    Code (CSharp):
    1. using UnityEngine
    2.  for (int i = 0; i <= puzzlePieces.Length; i++)
    3.         {
    4.             for (int j = 0; j <= images.Length; j++)
    5.             {
    6.                 puzzlePieces[i].sprite = Images[j];
    7.  
    8.  
    9.             }
    10.  
    11.         }
    12.  
     
  5. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    You don't need to nest a for loop, you can just use your i value for both of them.
     
    dcagemodels and Bunny83 like this.
  6. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,002
    To be more clear: You must not nest them as the code would not make any sense this way ^^. Also the code need to use
    <
    , not
    <=
     
    dcagemodels likes this.
  7. dcagemodels

    dcagemodels

    Joined:
    Nov 26, 2018
    Posts:
    14
    only repeats 1 image and does not cycle through all of them.
     

    Attached Files:

  8. dcagemodels

    dcagemodels

    Joined:
    Nov 26, 2018
    Posts:
    14
    Thank you for the guidance
     
  9. dcagemodels

    dcagemodels

    Joined:
    Nov 26, 2018
    Posts:
    14
    Thank you for the guidance.