Search Unity

Get saved position for each object in foreach loop

Discussion in 'Scripting' started by ellenblomw, May 11, 2019.

  1. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    123
    Hello guys,

    I have a list of gameobjects, and have managed to save each transform.position into a list like this:
    Code (CSharp):
    1.     private GameObject[] appleList;
    2.     public List<Vector3> saveAppleList;
    3.  
    4. void Start (){
    5. saveAppleList = new List<Vector3>();
    6.         foreach (GameObject apple in appleList)
    7.         {
    8.             saveAppleList.Add(apple.transform.position);
    9.             Debug.Log(saveAppleList);
    10.         }
    11. }
    Now I want to reposition my gameobjects into their saved start position. How do I do this? I have tried this but it just gives me lots of errors :p:
    Code (CSharp):
    1.         if (win == true) {
    2. foreach (GameObject apple in appleList)
    3.         {
    4.             apple.transform.position = saveAppleList.IndexOf();
    5.         }
    6. }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    2,147
  3. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    123
    Ok thank you for the advice, I'm not very used to for loops yet, I just started learning foreach. Something like this?
    Code (CSharp):
    1.         for (int i = 0; i < saveAppleList.Count; i++)
    2.         {
    3.             apple.transform.position = new Vector3(saveAppleList);
    4.         }
    Do you know the answer to my question btw, how to get the value from the savedAppleList for each apple? AKA the part inside the brackets. Do I use Indexof?

    Respectfully, Ellen
     
    Last edited: May 11, 2019
  4. BambooHutGames

    BambooHutGames

    Joined:
    Jun 7, 2017
    Posts:
    144
    Code (CSharp):
    1.   for (int i = 0; i < appleList.Count; i++)
    2.         {
    3.             appleList[i].transform.position = saveAppleList[i];
    4.         }
    Btw a somewhat better solution would be to handle all that in the apple class itself. then youwould only need one list that kkeps track of the apples and calls the function, no danger of messing up the order, you could just use a foreach loop:

    Code (CSharp):
    1. public class Apple : MonoBehaviour
    2. {
    3.     private Vector3 position;
    4.  
    5.     public void SavePosition()
    6.     {
    7.         position = transform.position;
    8.     }
    9.  
    10.     public void LoadPosition()
    11.     {
    12.         transform.position = position;
    13.     }
    14. }
     
    GroZZleR likes this.
  5. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    123
    Thank you very much Bamboo! Worked like a charm