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

Save last value of a variable in Update()

Discussion in 'Scripting' started by Federica_96, Apr 26, 2021.

  1. Federica_96

    Federica_96

    Joined:
    Feb 19, 2021
    Posts:
    30
    Hi,
    I have a variable in the Update() that updates its value at each frame. I have to pass this variable to another function of my script but when I do so the system crashes.

    I'd like to know if there is a way to get / save the last value assumed by this variable and then pass it to the other function.

    Thank you
     
  2. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    This is what the private field does
     
    Federica_96 likes this.
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,883
    If you could post an example of your code, using code tags, that will help us with the problem at hand.

    Though to answer in a broad sense, having a variable declared outside your Update class and other method classes will allow all of them to access that value.

    If the method is being called by your update class, you just need to pass the variable through method call, detailed like so (not sure if you're using C# or not: https://docs.microsoft.com/en-us/dotnet/csharp/methods#passing-parameters
     
  4. Federica_96

    Federica_96

    Joined:
    Feb 19, 2021
    Posts:
    30
    @spiney199 Thank you for your reply. This an example of my code (posted only the parts and the variables that give me problems)

    Code (CSharp):
    1. public class EyeRecords : MonoBehaviour
    2. {
    3.     public float xL_PixText_Remap, xR_PixText_Remap;
    4.    
    5.  
    6.     void Update()
    7.     {
    8.         xL_PixText_Remap = xL_pixText + 306;
    9.    
    10.         xR_PixText_Remap = xR_pixText + 306;
    11.  
    12.     }
    13.  
    14.     private void UpdateFilter(byte[] framebuffer)
    15.     {
    16.         newdstMat.put((int)xL_PixText_Remap, (int)xR_PixText_Remap, new byte[] { 127, 255, 0, 255 });
    17.  
    18.     }
    19.  
    20. }
    When I hit play the system crashes. That's because it reads too many values?
     
    Last edited: Apr 26, 2021
  5. MartinMa_

    MartinMa_

    Joined:
    Jan 3, 2021
    Posts:
    455
    Or you can save this variable to static class.
     
    Federica_96 likes this.