unity简单理解保存场景和载入场景

转载:https://blog.csdn.net/kmyhy/article/details/78643293

概念

在 Unity 中关于保存,有 4 个关键的概念:

PlayerPrefs: 这是一个特殊的缓存系统,在两次游戏过程中为玩家保存简单设定。许多新手程序员误以为他们能够用它来保存游戏存档,但这不是什么好的做法。它只允许你保存简单的东西,比如图形声音设置、登录信息或者其它基本的用户相关的数据。
序列化:这是 Unity 真正用到的关键点。序列化将对象转换成字节流。听起来有点抽象,你可以看看这张图:

什么是“对象”?在这里“对象”是 Unity 中的任意脚本或文件。事实上,当你创建一个 MonoBehaviour 脚本时,Unity 会通过序列化/反序列化将文件转换成 C++ 代码,然后变成你在检查器窗口中看见的 C# 代码。如果你曾经添加过 [SerializeField] 让某些东西在检查器中显示出来,你就知道怎么回事了。

注意:如果你是一个 Java 或者 web 开发者,你可能熟悉 marshalling (编码解码)的概念。序列化和 marshalling 是几乎是同义词,如果你硬要说它们有什么不同,序列化是将对象从一种对象转换成另一种形式(比如,对象->字节),而 marshalling 是让参数从一个地方传到另一个地方。

反序列化:就是它的名字所暗示的。它是序列化反面,将一个字节流转换成对象。
JSON:全称是 JavaScript Object Notation,是一种语言无关的发送和接收数据的常用格式。例如,你可能有一个运行在 Java 或者 PHP 下面的 web 服务器。你不能发送 C# 对象给它,但你可以发送这个对象的 JSON 形式给它,服务器会用它来重新创建一个本地版本的对象。后面的内容中你会学习更多关于这方面的内容,现在你只需要理解它是一种简单的格式化数据让它能够跨平台的方法(就像 XML)。当进行“对象->JSON”和“JSON->对象”转换时,可以分别将这两种称作称作 JSON 序列化和JSON 反序列化。

Player Prefs

Save.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;


[Serializable]
public class Save  
{
    public int score = 0;

}

pPlayMusicSetting.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayMusicSetting : MonoBehaviour
{
    [SerializeField]
    private Toggle toggle;
    [SerializeField]
    private AudioSource audioSource;

    private void Awake()
    {
        if(!PlayerPrefs.HasKey("music"))
        {
            PlayerPrefs.SetInt("music", 1);
            toggle.isOn = true;
            audioSource.enabled = true;
            PlayerPrefs.Save();
        }
        else
        {
            if(PlayerPrefs.GetInt("music")==1)
            {
                toggle.isOn = true;
                audioSource.enabled = true;
            }
            else
            {
                toggle.isOn = false;
                audioSource.enabled = false;
            }
        }
    }

    public void settingMusic()
    {
        if(toggle.isOn)
        {
            PlayerPrefs.SetInt("music", 1);
            audioSource.enabled = true;
        }
        else
        {
            PlayerPrefs.SetInt("music", 0);
            audioSource.enabled = false;
        }
        PlayerPrefs.Save();
    }
}

利用BinaryFormatter保存数据和json格式保存数据

在这里插入图片描述

game.cs

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;

public class game : MonoBehaviour
{
    public int scores = 0;

    public Text scoreText;

    public Button loadButton;
    public Button saveButton;
    public Button gainButton;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void GainGameobject()
    { 
        scores++;
        scoreText.text = "live:" + scores;                              
    }
    //初始化save类中所有的数据
    private Save CreateSaveGameObject()
    {
        Save save = new Save();
        save.score = scores;
        return save;
    }

    public void SaveGame()
    {
        Save save = CreateSaveGameObject();
        //使用BinaryFormatter二进制序列化存数据
        BinaryFormatter bf = new BinaryFormatter();
        //persistentDataPath包含持久数据目录的路径(只读)
        FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
        //将对象序列化给对应的流
        bf.Serialize(file, save);
        //关闭文件
        file.Close();

        scores = 0;
        scoreText.text = "live:" + scores;
        print("game save");

    }

    public void LoadGame()
    {
        if(File.Exists(Application.persistentDataPath+"/gamesave.save"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save", FileMode.Open);
            Save save = (Save)bf.Deserialize(file);
            file.Close();            
            scoreText.text = "score:" + save.score;
            scores = save.score;
            print("game save");
            SaveAsJSON();
        }
        else
        {
            print("no game save");
        }
    }
    //保存为json格式
    public void SaveAsJSON()
    {
        Save save = CreateSaveGameObject();
        //创建json字符串
        string json = JsonUtility.ToJson(save);
        // JSON 转换成一个 Save 对象
        //Save save = JsonUtility.FromJson<Save>(json);
        print("Saving as JSON:" + json);
    }
}


Unity 中,可以通过使用PlayerPrefs和Serialization来保存载入游戏。 PlayerPrefs是一个简单的键值对存储,可以用来存储玩家的偏好设置、游戏进度等信息。使用PlayerPrefs保存数据时,需要指定一个唯一的键名和对应的值,例如: ``` PlayerPrefs.SetInt("Level", 3); PlayerPrefs.SetString("PlayerName", "Tom"); ``` 使用Serialization可以将游戏对象和场景保存文件中,再在需要时将它们载入并还原。使用Serialization保存数据时,需要定义一个Serializable类来存储数据,例如: ``` [System.Serializable] public class GameData { public int level; public string playerName; } GameData data = new GameData(); data.level = 3; data.playerName = "Tom"; BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Create(Application.persistentDataPath + "/game.dat"); bf.Serialize(file, data); file.Close(); ``` 在这个示例中,我们定义了一个GameData类来存储游戏数据,然后使用BinaryFormatter将GameData对象序列化为二进制数据并保存文件中。 要载入保存的数据,可以使用以下代码: ``` if (File.Exists(Application.persistentDataPath + "/game.dat")) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/game.dat", FileMode.Open); GameData data = (GameData)bf.Deserialize(file); file.Close(); // 使用data中的数据还原游戏状态 } ``` 在这个示例中,我们首先检查保存数据的文件是否存在,如果存在则使用BinaryFormatter从文件中读取数据并将其反序列化为GameData对象,然后使用GameData中的数据还原游戏状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值