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

    Jonnystar99

    Joined:
    Mar 2, 2024
    Posts:
    1
    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:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SharedR : MonoBehaviour
    6. {
    7.     public int Highscore;
    8.     public logicscript logic;
    9.  
    10.     void Start() {
    11.        
    12.         logic.playScore = 0;
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         if (logic.playScore >= Highscore && logic.playScore > 0)
    19.         {
    20.             Highscore = logic.playScore;
    21.          
    22.         }
    23.         Debug.Log("Highscore: " + Highscore);
    24.     }
    25. }
    and:
    public class logicscript : MonoBehaviour
    {
    public int playScore = 0;

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

    public void restartGame()
    {
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
     
  2. flashframe

    flashframe

    Joined:
    Feb 10, 2015
    Posts:
    812
    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.

    https://docs.unity3d.com/ScriptReference/PlayerPrefs.html



    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.

    https://unity.com/how-to/separate-game-data-logic-scriptable-objects#:~:text=ScriptableObjects shine when many objects,values individually on every GameObject.