Search Unity

Arrays won't update properly

Discussion in 'Scripting' started by sergiumarcu97, Aug 18, 2019.

  1. sergiumarcu97

    sergiumarcu97

    Joined:
    Aug 18, 2019
    Posts:
    2
    So I'm currently trying to figure out the movement of my character. I am making a 2D platformer and I'm trying to make it so that if the character gets stuck on the x axis while receiving movement input, he'll get pushed upwards instead (e.g. I jump and land on the side of a platform, character gets stuck, so while still holding d I want the character to get up so that he can land on the platform).
    My approach was to create an array of 2, and in the start function initialize a[1] with my current x position:
    arr[0] = 0; arr[1] = rb2d.position.x;

    In the update function I have set an if statement to calculate if a certain amount of time has passed as I don't want this check to be made continuously, only .1 seconds for example. So I'm testing it with 2 seconds right now :
    Code (CSharp):
    1. if (System.Math.Round(timePassed,1) % 2 == 0)
    2.         {
    3.             arr[0] = arr[1];
    4.             arr[1] = rb2d.position.x;
    5.             Debug.Log("arr 0 is " + arr[0]);
    6.             Debug.Log("arr 1 is " + arr[1]);
    7.  
    8.         }
    The problem I encounter is both array elements get the same value each time they get updated:


    Any solution, alternatives or code checking is highly appreciated!
    Thank you, Sergiu.
     
  2. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,619
    According to the time in your log, they get different values:
    upload_2019-8-18_11-6-28.png
    It looks correct to me. arr0 receives the value from the previous arr1 element, that's why they seem to appear in pairs.
     
  3. gononono64

    gononono64

    Joined:
    Mar 1, 2015
    Posts:
    13
    Yeah looks good to me its just printing backwards
     
  4. sergiumarcu97

    sergiumarcu97

    Joined:
    Aug 18, 2019
    Posts:
    2
    Wow, given my previous experience with modifying the code 100 times I believed it still prints the same values for each array element. I was only looking for the values and not the timestamp. Guess it's something to learn from. Thank you guys!