![](/img/trans.png)
[英]How can I Transfer my Score Game Object from my game scene to game over scene in Unity
[英]how can i retain my player score to a new scene?
我有一個簡單的腳本來為玩家計算一個分數,如何獲得該值並將其顯示在游戲中?
這是我的分數腳本:
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;
}
}
退出當前場景時將其存儲在PlayerPrefs
,將其保存在playerpref中,例如:
PlayerPrefs.Setint(" CurrentScore",scoreValue);
然后通過以下方式在新場景中進行檢索:
scoreValue = PlayerPrefs.Getint(" CurrentScore");
很簡單,只需在游戲場景中所需的任何腳本中調用“ scoreScript.scoreValue”
您已經將其設置為public static
,剩下的就是在游戲中通過場景的文本字段腳本進行編寫:
gameOverText.text = "Score: " + scoreScript.scoreValue;
假設gameOverText
是Text
。
您無需創建實例即可訪問靜態成員,而應使用類名稱(在本例中為scoreScript
)訪問它們。
但是,混合存儲全局得分和用於在單個類中顯示它的textField並不是很好,因為在向游戲添加新功能時,所有全局變量都將位於不同的類中,並且在修改自己的代碼時您將越來越關注碼。 為避免這種情況,可以將靜態類用作存儲所有全局變量的“核心”。 這將是第一次。
DontDestroyOnLoad
工作與GameObject
S,所以當加載一個新的場景,他們將不被破壞。 如果在腳本中調用它,則計分GameObject的分數將保留,而文本字段也將保留,因為它是該對象的組合,並且會出現在游戲場景中,因此不要這樣做。
當您加載新場景時,帶有“ scoreScript”的gameObject將丟失。 為了將相同的游戲對象轉移到新的場景(為了避免丟失腳本所攜帶的信息,這是有意義的),您需要使用“ DontDestroyOnLoad”方法。 您只需在單行為的Awake方法中調用該方法,然后您的游戲對象(以及腳本中的數據)將繼續新的場景加載。 以下是相關文檔: https : //docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
這是一個代碼示例:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.