简体   繁体   中英

how can i retain my player score to a new scene?

I have a simple script to count up a score for the player, how can I take this value and display it on a game over scene?

This is my score script:

public class scoreScript : MonoBehaviour {

 public static int scoreValue = 0;
 Text score;

 // Use this for initialization
 void Start () {
     score = GetComponent<Text>();
 }

 // Update is called once per frame
 void Update () {
     score.text = "Score:" + scoreValue;
 }

}

Store it in PlayerPrefs while you exit current scene save it in playerpref like :

PlayerPrefs.Setint(" CurrentScore",scoreValue);

then retrive it in new scene by :

scoreValue = PlayerPrefs.Getint(" CurrentScore");

很简单,只需在游戏场景中所需的任何脚本中调用“ scoreScript.scoreValue”

You already made it public static , all that's left is to write in your game over scene's text field script:

gameOverText.text = "Score: " + scoreScript.scoreValue;

assuming that gameOverText is a Text .

You don't need to create an instance to access a static member, you should access them using a class name ( scoreScript in your case).

However, it's not good to mix storing global score and a textField for displaying it in a single class, because as you add new features to the game, all global variables will be in different classes, and you will pay increasingly more attention while modifying your code. To avoid this, you may use a static class as a "core" where you store all global variables. For the first time, this will do.

DontDestroyOnLoad works with GameObject s, so they will not destroyed when a new Scene is loaded. If you call it in your script, your score counting GameObject will remain, and so will a text field because it's a compoment of that object, and will be present on game over scene, so don't do it.

When you are loading a new scene, the gameObject that carries the "scoreScript" is lost. In order to transfer the same gameobject to a new scene (which makes sense in order to not lose your information that the script is carrying), you need to use the "DontDestroyOnLoad" method. You just call the method in the Awake method of your monobehaviour, and then your gameobject (together with the data on your script) will persist new scene loading. Here is the relevant documentation: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

and here is a code sample:

public class scoreScript : MonoBehaviour {
    public static int scoreValue = 0;
    Text score;

    void Awake(){
        DontDestroyOnLoad(this.gameObject);
    }

    void Start () {
        score = GetComponent<Text>();
    }

    void Update () {
        score.text = "Score:" + scoreValue;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM