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

How can you store Global variables not in UI?

Discussion in 'Scripting' started by reppeti, May 9, 2022.

  1. reppeti

    reppeti

    Joined:
    Jun 29, 2021
    Posts:
    44
    Hello everyone!

    This might be a dumb but currenty I have a game that has money and levels. Currently when I want to add money or substract money I just change the Text field. Badically I use the text field as a variable, but I feel like that's not the way to go. How should I do it instead?
     
  2. FlashMuller

    FlashMuller

    Joined:
    Sep 25, 2013
    Posts:
    449
    No Copy Paste answer, but something to dig into:
    Check out PlayerPrefs (as an easy start) for saving variables between levels or gaming sessions.
    Easiest SetUp would be PlayerPrefs.GetXYZ() on Start and PlayerPrefs.SetXYZ() on your preferred timing (do NOT use it in Update() though).
    It's very straight forward: Unity - Scripting API: PlayerPrefs (unity3d.com)

    You should also dig into the concept of Singletons (in Combination with DontDestroyOnLoad) to have a single place of storing and using global Variables and also keeping them between levels.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,883
    Many ways to do so.

    The most basic way would be a static variable.
    Code (CSharp):
    1. public class MoneyUIManager : MonoBehaviour
    2. {
    3.     public static int MoneyTotal;
    4. }
    The above has an integer that can be accessed anywhere, though can only exist once. You can pass that value to your text field rather than storing the value inside.

    Alternatively you could look at scriptable objects. A simple scriptable object that holds some public fields can then be referenced where it's needed to assign and pull data without tight coupling to a certain class' certain static field.

    Edit: Counter to the above, player prefs should NOT be used for progression save data or to transmit data between objects.
     
    reppeti likes this.
  4. reppeti

    reppeti

    Joined:
    Jun 29, 2021
    Posts:
    44
    Thanks scalie friend!

    I'll try to switch to one of these in my game.