Search Unity

Using static variables to pass data between scenes. [Android]

Discussion in 'Scripting' started by TreesAreGood, Apr 19, 2021.

  1. TreesAreGood

    TreesAreGood

    Joined:
    Nov 7, 2020
    Posts:
    2
    I need a non-complex solution to pass 1 integer to another scene. Using JSON or binary formatter seems too sophisticated for this simple task.

    Static variables seem to persist between scenes, which would be an ideal solution, considering, that I won't need this variable anymore after accessing it for the first time.

    But my question would be: is it safe to use statics in this way? I mean, in android build it does work as in the editor, but could there be something in the long run, that I don't know about right now?
     
  2. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    Static variables will work the same in Android as they do in the editor. As long as you keep in mind that the value of a public static field variable can be changed from anywhere within the program then you'll be fine.

    I usually implement them as properties, so that I can restrict the scope that they can be set or use the stack trace from the setter to help me track down where a static variable with a public setter is being updated if I need to find a bug related to it.
     
    Last edited: Apr 19, 2021
  3. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    They're safe to use.

    A static member simply means it is not tied to any instance of an object, and they live in-memory instead.
    I.E: You don't need to instantiate an object to access the static member.

    You're likely already using static members in your project as well (Random.Range, Time.deltaTime, Mathf.Clamp, etc.).
     
  4. SaltwaterAssembly

    SaltwaterAssembly

    Joined:
    Mar 8, 2016
    Posts:
    95
    Why not use scriptable objects?