Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How can I share variables between scenes and use them in player Pref

I am a New person to Unity. My problem is that I have a Score in my first scene which is the position of z of the player. I want it to save it to the HighScore using PlayerPrefs. I have 2 empty objects named MenuManager and GameManager and they have their own scripts but I don't know how can I share the value of the score and save it in a PlayerPrefs. Can anyone please help me? I don't know how can I assign a component if it is not in my scene. Also can you please help me to use the function of a script of a different scene. I mean how can I call a function of a game object which is in an other scene. Please help me. I need to finish my game.

The Score Script which keeps track of players position.

using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{
    public Transform player;
    public Text scoreText;
    public HighScore highScore;

    [HideInInspector]public static float totalScore;

    void Update()
    {
        scoreText.text = player.position.z.ToString("0");
        totalScore = player.position.z;
    }
}

The High Score Script which is responsible for the text changing although I havent worked on the player prefs yet if anyone knows please help me in that also.

using UnityEngine;
using UnityEngine.UI;

public class HighScore : MonoBehaviour
{
    static float floatScore;
    public Text highScore;

    private void Start()
    {
        highScore.text = PlayerPrefs.GetFloat("HighScore", 0).ToString();
    }
    public void highScoreFunc()
    {  
        PlayerPrefs.SetFloat("HighScore", floatScore);
        highScore.text = floatScore.ToString();
    }

    public void resetScore()
    {
        PlayerPrefs.DeleteKey("HighScore");
    }
}

The Menu Functions Script which have the option of using the buttons.

using UnityEngine;
using UnityEngine.SceneManagement;

public class MenuFunctions : MonoBehaviour
{

    public void StartGame()
    {
        SceneManager.LoadScene(1);
    }

    public void quitGame()
    {
        Application.Quit();
    }
}

The Game Manager which have the work of changing scenes and restarting the game.

using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    bool GameEnd = true;
    public HighScore highScore;
    

    public void EndGame()
    {
        if(GameEnd)
        {
            GameEnd = false;
            Invoke("Restart", 1);
        }
    }
  
    void Restart()
    {
        SceneManager.LoadScene(sceneBuildIndex: 0);
    }
}


Best Answer

  • HNJHNJ Member
    Accepted Answer

    If you want to use a Variable of a script from other script, just do,


    ClassName.variable;
    


    make sure that variable is public.

Sign In or Register to comment.