DIVINEMADNEZZ
DIVINEMADNEZZ

Reputation: 11

How to save a float between scenes in unity

Hi there I am very new to code and I'm really struggling. I'm just trying to create a simple bet system for a blackjack game, in which you place your bet and the value is saved then it gets carried into my next scene which would be the game scene. So basically I created a button in a scene called BetScene when the button is pressed it adds 25 to the betamount and removes 25 from the playeramount. Once the player is happy with the money they placed they press the second button PlaceBet. When that button gets pressed the game scene loads so what I want to do is save the amount that was placed and display it in the game scene. Hope this makes sense I really need help I'm really trying to learn thanks

Upvotes: 0

Views: 662

Answers (2)

Max Play
Max Play

Reputation: 4037

Okay, so first: This scenario does not sound like you should use multiple scenes, so I would say "reconsider your architecture and scene flow in this case." But I am also here, to answer your question, so let's do that instead.

A great way of sharing data between scenes is using a ScriptableObject as a data container. You simply create the class of the data you want to use in multiple scenes and then create an instance of your ScriptableObject as an asset in your Assets-folder.
This asset can then be assigned to all components that need to use it for data transfer. It is basically like a texture that is painted on in one scene and read from in another scene.

You can even improve on this by creating a kind of "data binding" using these ScriptableObject assets as variables. There is a great talk about that topic from 2017 on Unitys YouTube channel: Unite Austin 2017 - Game Architecture with Scriptable Objects

Upvotes: 2

Tiny Brain
Tiny Brain

Reputation: 640

Solution 1: Using PlayerPrefs.

PlayerPrefs.SetFloat("HIGHSCORE", 123.45f);
float highscore = PlayerPrefs.GetFloat("HIGHSCORE");

Solution 2: Using Static Instance

public class MyClass: MonoBehavior {
  public static MyClass Instance;
  public float highscore;
  void Awake() {
    Instance = this;
    DontDestroyOnLoad(this);
  }
}
...
public class YourClass: MonoBehavior {
  void YourFunction() {
    print(MyClass.Instance.highscore);
  }
}

Upvotes: 0

Related Questions