如何在 Unity 中的场景之间传递数据(和引用) [英] How to pass data (and references) between scenes in Unity

查看:99
本文介绍了如何在 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 开发游戏(意味着游戏将在安卓设备上运行).

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.

您可以创建一个空的游戏对象,并只将包含您想要保留的变量的脚本放置在其上.

You could create an empty GameObject, and place only the script containing the variables you want preserved on it.

这篇关于如何在 Unity 中的场景之间传递数据(和引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆