统一加载另一个场景时将int变量重置 [英] int variable resetting when loading another scene in unity

查看:109
本文介绍了统一加载另一个场景时将int变量重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个足球比分计算器.我有一个可以更改场景的按钮,但是当我更改场景并重新打开它时,得分值将重置为0.这是代码:

I created a football score calculator. I have a button that changes the scene, but when I change the scene and reopen it the score value is reset to 0. Here is the code:

public class Main : MonoBehaviour {
    public Text plusUp;
    public int value = 0;

    public void button(int sc)
    {
        SceneManager.LoadScene(sc);
    }

    public void plus()
    {
        value++;
        plusUp.text = value.ToString();
    }
}

推荐答案

1..可以在保存要保存变量的对象上使用方法Object.DontDestroyOnLoad.加载另一个场景时,它将保持GameObject该脚本的附加状态:

1. You can use the method Object.DontDestroyOnLoad on the object that hold the variable you want to save. It will keep the GameObject this script is attached too alive when another scene is loaded:

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

有关更多信息,请参见文档

See the documentation for more informations

您也可以制作一个Singleton,但是这种设计模式稍微复杂一点,因为在加载另一个场景时Unity会销毁它.您仍然必须使用DontDestroyOnLoad来了解如何在其 GitHub页面

You can also make a Singleton but this design pattern is a little more complex as Unity will destroy it when you load another scene. You still have to use DontDestroyOnLoad see how to implement this pattern on their GitHub page

2..或者,您可以在加载另一个场景之前将值保存在磁盘上,然后使用PlayerPrefs辅助方法加载该值:

2. Or you can save the value on the disk before loading another scene and then load the value with PlayerPrefs helpers methods:

public int value = 0;

void Awake()
{
    //Load the saved score (this value will be saved even if you restart the app)
    value = PlayerPrefs.GetInt("Score");
}

public void button1(int sc)
{
    //Save your value before you load the scene
    PlayerPrefs.SetInt("Score", value);
    SceneManager.LoadScene(sc);
}    

有关类型的更多信息,请参见文档.

See the documentation for more informations on the types.

这篇关于统一加载另一个场景时将int变量重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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