如何在Unity中的场景之间传递数据 [英] How to pass data between scenes in Unity
问题描述
如何将得分值从一个场景传递到另一个场景?
How can I pass score value from one scene to another?
我尝试了以下操作:
场景一:
void Start () {
score = 0;
updateScoreView ();
StartCoroutine (DelayLoadlevel(20));
}
public void updateScoreView(){
score_text.text = "The Score: "+ score;
}
public void AddNewScore(int NewscoreValue){
score = score + NewscoreValue;
updateScoreView ();
}
IEnumerator DelayLoadlevel(float seconds){
yield return new WaitForSeconds(10);
secondsLeft = seconds;
loadingStart = true;
do {
yield return new WaitForSeconds(1);
} while(--secondsLeft >0);
// here I should store my last score before move to level two
PlayerPrefs.SetInt ("player_score", score);
Application.LoadLevel (2);
}
第二种情况:
public Text score_text;
private int old_score;
// Use this for initialization
void Start () {
old_score = PlayerPrefs.GetInt ("player_score");
score_text.text = "new score" + old_score.ToString ();
}
但屏幕上没有任何显示,也没有错误.
but nothing displayed on screen, and there's no error.
这是传递数据的正确方法吗?
Is this the correct way to pass data ?
我正在使用Unity 5免费版,为Gear VR开发游戏(这意味着该游戏将在android设备上运行).
I am using Unity 5 free edition, develop game for Gear VR (meaning the game will run in android devices).
有什么建议吗?
推荐答案
playerPrefs的另一种肮脏方式是在关卡加载期间通过调用对象DontDestroyOnLoad来保留对象.
Besides playerPrefs another dirty way is to preserve an object during level loading by calling DontDestroyOnLoad on it.
DontDestroyOnLoad (transform.gameObject);
任何附加到游戏对象上的脚本都将保留,脚本中的变量也将保留. DontDestroyOnLoad函数通常用于保留整个GameObject,包括与其相连的组件以及它在层次结构中具有的所有子对象.
Any script attached to the game object will survive and so will the variables in the script. The DontDestroyOnLoad function is generally used to preserve an entire GameObject, including the components attached to it, and any child objects it has in the hierarchy.
您可以创建一个空的GameObject,然后仅将包含要保留的变量的脚本放在其上.
You could create an empty GameObject, and place only the script containing the variables you want preserved on it.
这篇关于如何在Unity中的场景之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!