简体   繁体   English

C#-Unity3d在游戏中保存一些变量?

[英]C# - Unity3d save some variables in game?

I would make sure when I close The Game , he saved automatically some variables ( scores ), and show them once started ? 我确定当我关闭游戏时,他会自动保存一些变量(分数),并在开始时显示它们吗?

To do this i need to use these to save an float? 为此,我需要使用它们来保存浮点数?

void Awake
void Load

or i need these? 还是我需要这些?

public void Load
public void Save

can you show me some example code line that works? 您能告诉我一些可行的示例代码行吗? thanks 谢谢

A good option for that is to use the OnEnable and OnDisable event functions . 一个不错的选择是使用OnEnableOnDisable 事件函数

using UnityEngine;

public class GameSaver : MonoBehaviour
{
    int _score;

    void OnEnable()
    {
         _score = PlayerPrefs.GetInt("Player Score");
    }

    void OnDisable()
    {
         PlayerPrefs.SetInt("Player Score", score);
    }

    void Update()
    {
        // change the _score during the game execution.
    }
}

Make sure that the object you attach the script to exists throughout the whole game. 确保附加脚本的对象在整个游戏中都存在。 You also could call those functions manually from your code when you need it. 您还可以在需要时从代码中手动调用这些函数。

Of course, you could create your own methods called Load and Save or Serialize and Deserialize and then call them from OnEnable and OnDisable , like that: 当然,您可以创建自己的名为Load and SaveSerialize and Deserialize ,然后从OnEnableOnDisable调用它们,如下所示:

void OnEnable()
{
    Load();
}

void Load()
{
    _score = PlayerPrefs.GetInt("Player Score");
} 

This will look better from the prorgammers point of view, but the program will work pretty much the same way. 从程序员的角度来看,这看起来会更好,但是该程序的工作方式几乎相同。

You may also prefer to use the methods like Awake and OnApplicationQuit , but you still would need your game object to be alive from start to end, so this does not make much sense. 您可能还喜欢使用AwakeOnApplicationQuit类的方法,但是您仍然需要游戏对象OnApplicationQuit都处于活动状态,所以这没有太大意义。

If you need to save more than just a few variables, you might want to take a look at the so called Unity Serializer . 如果您需要保存的不仅仅是几个变量,那么您可能需要看一下所谓的Unity Serializer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM