场景变更后如何保持设定

问题描述

我在1个场景中都有一个选项菜单,但是当您加载到游戏中(切换场景)然后又回来(切换场景)时,它将丢失所有设置。我试图用DontDestroyOnLoad做到这一点,但无法使其正常工作,我无法弄清楚如何读写文本文件。保留所有设置的最佳方法是什么? 图片Here

解决方法

在Unity中,您可以通过PlayerPrefs类保存和加载设置。这是一个静态类,这意味着您可以在Unity脚本文件中的任何位置访问设置。

用法示例:

// Set the player name preference
PlayerPrefs.SetString("player_name","Darian Benam");

// Save all the preferences
PlayerPrefs.Save();

// Load the player name from the preferences
string playerName = PlayerPrefs.GetString("player_name"); // According to this example,the value of the string will be "Darian Benam"

需要在脚本的Start()方法中重新加载菜单场景中的设置。您只需要将GUI组件的值设置为PlayerPrefs类中的getter方法的返回值即可。