Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question How can i save values over scenes

Discussion in 'Getting Started' started by Jonnystar99, Mar 2, 2024.

  1. Jonnystar99


    Mar 2, 2024
    I made my first game, it is a rip off of flappy bird and want to make a highscore that needs to be saved over the scenes. Since when my bird dies i reset the scene.
    The problem is:
    NullReferenceException: Object reference not set to an instance of an object
    SharedR.Start () (at Assets/SharedR.cs:12)

    So how can i save values over a scene, since i cant make code in another scene to prevent it.
    SharedR is in another scene

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class SharedR : MonoBehaviour
    6. {
    7.     public int Highscore;
    8.     public logicscript logic;
    10.     void Start() {
    12.         logic.playScore = 0;
    13.     }
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         if (logic.playScore >= Highscore && logic.playScore > 0)
    19.         {
    20.             Highscore = logic.playScore;
    22.         }
    23.         Debug.Log("Highscore: " + Highscore);
    24.     }
    25. }
    public class logicscript : MonoBehaviour
    public int playScore = 0;

    public void addScore() {
    scoreText.text = playScore.ToString();

    public void restartGame()
  2. flashframe


    Feb 10, 2015
    Lots of ways to do this. Many people start out using player prefs. This has the advantage of being very quick to set up and test, and the data persists between sessions.

    As your game scales, you might need something more flexible. A good option is to use scriptable objects to hold data that can be referenced within different scenes. Scriptable objects live in the project, so they are great containers for shared data. Just be aware that if you want the data to persist between sessions of your game, you’ll need to save it to a file and restore it later. shine when many objects,values individually on every GameObject.