我想保存一些变量的值。我试图将其保存到文件中,但它不起作用。所以现在我用另一种方式尝试。但它也不会保存数据... 如果我启动模拟i Unity,更改变量的值,停止模拟然后重新启动它,我有变量的旧值。
void OnEnable()
{
LoadFromFile();
}
void OnDisable()
{
SaveToFile();
}
public void SaveToFile()
{
GameObject gameManagerObject = GameObject.FindGameObjectWithTag("GAMEMANAGER");
GAMEMANAGER gameManager = gameManagerObject.GetComponent<GAMEMANAGER>();
IndicatorsInfo indicatorsInfo = new IndicatorsInfo();
PlayerPrefs.SetFloat("my_setting", indicatorsInfo.walkSpeedTemfFile);
}
public void LoadFromFile()
{
GameObject gameManagerObject = GameObject.FindGameObjectWithTag("GAMEMANAGER");
GAMEMANAGER gameManager = gameManagerObject.GetComponent<GAMEMANAGER>();
gameManager.walkSpeedTemp = PlayerPrefs.GetFloat("my_setting");
}
[Serializable]
class IndicatorsInfo
{
public float walkSpeedTemfFile;
}
IndicatorsInfo indicatorsInfo = new IndicatorsInfo(); PlayerPrefs.SetFloat("my_setting", indicatorsInfo.walkSpeedTemfFile);
使用 new
关键字时,您正在创建IndicatorsInfo
的新实例。您保存了该新实例中的indicatorsInfo.walkSpeedTemfFile
,但没有为您创建的新indicatorsInfo
赋值。
也许您要做的是从编辑器中保存值?
GameObject gameManagerObject = GameObject.FindGameObjectWithTag("GAMEMANAGER");
GAMEMANAGER gameManager = gameManagerObject.GetComponent<GAMEMANAGER>();
PlayerPrefs.SetFloat("my_setting", gameManager.walkSpeedTemp);