Per aspera ad astra.循此苦旅,以达天际。|

flyall

园龄:4年2个月粉丝:10关注:8

2023-03-06 01:35阅读: 60评论: 0推荐: 0

unity3D保存游戏20

保存按钮和加载按钮的实现

image

注册两个按钮

image

二进制方法存储

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }

    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
    }

    private void LoadBybin()
    {

    }

    private void SaveByXml()
    {

    }
    private void LoadByXml()
    {

    }
    private void SaveByJson()
    {

    }
    private void LoadByJson() { }

    public void ContinueGame()
    {
        UnPause();
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }
    //保存游戏
    public void SaveGame()
    {
        SaveBybin();
    }
    //加载游戏
    public void LoadGame()
    {

    }
}

二进制方法读取游戏

新建提示文字UI

image
image

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//2.获得UI
using UnityEngine.UI;

public class UIManager : MonoBehaviour
{
    //6.调用 
    public static UIManager _instance;
    //1.获得UItext
    public Text shootNumText;
    public Text scoreText;

    //4.初始化
    public int shootNum = 0;
    public int score = 0;

    //7.得到背景音乐选框
    public Toggle musicToggle;
    public AudioSource musicAudio;

    //得到uimessager
    public Text messageText;

//6.调用
private void Awake()
{
    _instance = this;
        if (PlayerPrefs.HasKey("MusicOn"))
        {
            if (PlayerPrefs.GetInt("MusicOn") == 1)
            {
                musicAudio.enabled = true;
            }
            else
            {
                musicAudio.enabled = false;
            }
        }
        else
        {
            musicAudio.enabled = true;
        }
}

//5.在update中实时更新数据
private void Update()
    {
        shootNumText.text = shootNum.ToString();
        scoreText.text = score.ToString();
     
    }
    //7.音乐开关
    public void MusicSwitch()
    {
        if (musicToggle.isOn == false)
        {
            musicAudio.enabled=false;
            //保存音乐开关的状态,0代表关闭
            PlayerPrefs.SetInt("MusicOn", 0); 
        }
        else{
            musicAudio.enabled=true;
            PlayerPrefs.SetInt("MusicOn", 1);

        }
            PlayerPrefs.Save();
    }
    //3.方法
    public void AddShootNum()
    {
        shootNum += 1;
    }
    public void AddScore()
    {
        score += 1;
    }

    //文字
    public void ShowMessage(string str) 
    {
        messageText.text = str;
    }

}

赋值

image

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }

    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }

    private void LoadBybin()
    {

    }

    private void SaveByXml()
    {

    }
    private void LoadByXml()
    {

    }
    private void SaveByJson()
    {

    }
    private void LoadByJson() { }

    public void ContinueGame()
    {
    
        UnPause();
        UIManager._instance.ShowMessage("");
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UIManager._instance.ShowMessage("");

        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }

    //保存游戏
    public void SaveGame()
    {
        SaveBybin();
       
    }
    //加载游戏
    public void LoadGame()
    {
        UIManager._instance.ShowMessage("");
    }
}

加载

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }


    //设置
    private void SetGame(Save save)
    {
        //先将所有target里面的怪物清空 并重置所有的计时
        foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        //通过反序列化得到save对象中存储的信息,激活指定的怪物
        for(int i = 0; i < save.livingTargetPositions.Count; i++)
        {
            int position = save.livingTargetPositions[i];
            int type = save.livingMonsterTypes[i];

            targetGOs[position].GetComponent<TargetManager>().ActivateMonsterByType(type);
        }

        //更新UI显示
        UIManager._instance.shootNum = save.shootNum;
        UIManager._instance.score = save.score;

       
        UnPause();
    }


    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }

    private void LoadBybin()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            //反序列化过程
            //创建一个二进制格式化程序
            BinaryFormatter bf = new BinaryFormatter();
            //打开一个文件流
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
            //调用格式化程序的反序列化方法,将文件流转化为一个Save对象
            Save save = (Save)bf.Deserialize(fileStream);
            //关闭文件流
            fileStream.Close();

            SetGame(save)
			UIManager._instance.ShowMessage("");;
           
        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
       
    }

    private void SaveByXml()
    {

    }
    private void LoadByXml()
    {

    }
    private void SaveByJson()
    {

    }
    private void LoadByJson() { }

    public void ContinueGame()
    {
    
        UnPause();
        UIManager._instance.ShowMessage("");
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UIManager._instance.ShowMessage("");

        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }

    //保存游戏
    public void SaveGame()
    {
        SaveBybin();
       
    }
    //加载游戏
    public void LoadGame()
    {
        LoadBybin();
    }
}

JSON

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }


    //设置
    private void SetGame(Save save)
    {
        //先将所有target里面的怪物清空 并重置所有的计时
        foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        //通过反序列化得到save对象中存储的信息,激活指定的怪物
        for(int i = 0; i < save.livingTargetPositions.Count; i++)
        {
            int position = save.livingTargetPositions[i];
            int type = save.livingMonsterTypes[i];

            targetGOs[position].GetComponent<TargetManager>().ActivateMonsterByType(type);
        }

        //更新UI显示
        UIManager._instance.shootNum = save.shootNum;
        UIManager._instance.score = save.score;

       
        UnPause();
    }


    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }

    private void LoadBybin()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            //反序列化过程
            //创建一个二进制格式化程序
            BinaryFormatter bf = new BinaryFormatter();
            //打开一个文件流
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
            //调用格式化程序的反序列化方法,将文件流转化为一个Save对象
            Save save = (Save)bf.Deserialize(fileStream);
            //关闭文件流
            fileStream.Close();

            SetGame(save);
			UIManager._instance.ShowMessage("");
           
        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
       
    }

    private void SaveByXml()
    {

    }
    private void LoadByXml()
    {

    }
    private void SaveByJson()
    {
        Save save= CreateSaveGO();
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        //利用jsonmapper将save对象转换为json格式的字符串
        string saveJsonStr = JsonMapper.ToJson(save);
        //将字符串写入文件中 先建立streamWrite
        StreamWriter sw=new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        sw.Close();
        UIManager._instance.ShowMessage("保存成功");

    }
    private void LoadByJson() { }

    public void ContinueGame()
    {
    
        UnPause();
        UIManager._instance.ShowMessage("");
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UIManager._instance.ShowMessage("");

        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }

    //保存游戏
    public void SaveGame()
    {
        //SaveBybin();
        SaveByJson();
       
    }
    //加载游戏
    public void LoadGame()
    {
        LoadBybin();
    }
}

json读取

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }


    //设置 通过读档信息重置界面
    private void SetGame(Save save)
    {
        //先将所有target里面的怪物清空 并重置所有的计时
        foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        //通过反序列化得到save对象中存储的信息,激活指定的怪物
        for(int i = 0; i < save.livingTargetPositions.Count; i++)
        {
            int position = save.livingTargetPositions[i];
            int type = save.livingMonsterTypes[i];

            targetGOs[position].GetComponent<TargetManager>().ActivateMonsterByType(type);
        }

        //更新UI显示
        UIManager._instance.shootNum = save.shootNum;
        UIManager._instance.score = save.score;

       
        UnPause();
    }


    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }

    private void LoadBybin()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            //反序列化过程
            //创建一个二进制格式化程序
            BinaryFormatter bf = new BinaryFormatter();
            //打开一个文件流
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
            //调用格式化程序的反序列化方法,将文件流转化为一个Save对象
            Save save = (Save)bf.Deserialize(fileStream);
            //关闭文件流
            fileStream.Close();

            SetGame(save);
        UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
       
    }

    private void SaveByXml()
    {

    }
    private void LoadByXml()
    {

    }
    private void SaveByJson()
    {
        Save save= CreateSaveGO();
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        //利用jsonmapper将save对象转换为json格式的字符串
        string saveJsonStr = JsonMapper.ToJson(save);
        //将字符串写入文件中 先建立streamWrite
        StreamWriter sw=new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        sw.Close();
        UIManager._instance.ShowMessage("保存成功");

    }
    private void LoadByJson() 
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        if (File.Exists(filePath))
        {
            //创建一个streamReader,用来读取流
            StreamReader sr = new StreamReader(filePath);
            //将读取到的流赋值给jsonstr
            string jsonStr=sr.ReadToEnd();
            sr.Close();
            Save save = JsonMapper.ToObject<Save>(jsonStr);
            SetGame(save);
            UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
    }

    public void ContinueGame()
    {
    
        UnPause();
        UIManager._instance.ShowMessage("");
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UIManager._instance.ShowMessage("");

        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }

    //保存游戏
    public void SaveGame()
    {
        //SaveBybin();
        SaveByJson();
       
    }
    //加载游戏
    public void LoadGame()
    {
       // LoadBybin();
       LoadByJson();
    }
}

XML

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }


    //设置 通过读档信息重置界面
    private void SetGame(Save save)
    {
        //先将所有target里面的怪物清空 并重置所有的计时
        foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        //通过反序列化得到save对象中存储的信息,激活指定的怪物
        for(int i = 0; i < save.livingTargetPositions.Count; i++)
        {
            int position = save.livingTargetPositions[i];
            int type = save.livingMonsterTypes[i];

            targetGOs[position].GetComponent<TargetManager>().ActivateMonsterByType(type);
        }

        //更新UI显示
        UIManager._instance.shootNum = save.shootNum;
        UIManager._instance.score = save.score;

       
        UnPause();
    }


    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }

    private void LoadBybin()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            //反序列化过程
            //创建一个二进制格式化程序
            BinaryFormatter bf = new BinaryFormatter();
            //打开一个文件流
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
            //调用格式化程序的反序列化方法,将文件流转化为一个Save对象
            Save save = (Save)bf.Deserialize(fileStream);
            //关闭文件流
            fileStream.Close();

            SetGame(save);
        UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
       
    }

    private void SaveByXml()
    {
        Save save=CreateSaveGO();
        //存储路径
        string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
        //创建XML文档
        XmlDocument xmlDoc = new XmlDocument();
        //创建根节点
        XmlElement root = xmlDoc.CreateElement("save");
        //设置根节点的值
        root.SetAttribute("name", "saveFile1");
        //创建Xml元素
        XmlElement target;
        XmlElement targetPosition;
        XmlElement monsterType;
        //遍历save中存储的数据并转换成xml格式
        for(int i = 0;i<save.livingTargetPositions.Count;i++)
        {
            target = xmlDoc.CreateElement("target");
            targetPosition = xmlDoc.CreateElement("targetPosition");
            targetPosition.InnerText = save.livingTargetPositions[i].ToString();
            monsterType = xmlDoc.CreateElement("monsterType");
            monsterType.InnerText = save.livingMonsterTypes[i].ToString();
            //设置节点之间的层级关系
            target.AppendChild(targetPosition);
            target.AppendChild(monsterType);
            root.AppendChild(target);
        }
        //设置射击数和分数节点
        XmlElement shootNum = xmlDoc.CreateElement("shootNum");
        shootNum.InnerText = save.shootNum.ToString();
        XmlElement score = xmlDoc.CreateElement("score");
        score.InnerText = save.score.ToString();

        root.AppendChild(shootNum);
        root.AppendChild(score);

        xmlDoc.AppendChild(root);
        xmlDoc.Save(filePath);

        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byXML.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }
    private void LoadByXml()
    {

    }
    private void SaveByJson()
    {
        Save save= CreateSaveGO();
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        //利用jsonmapper将save对象转换为json格式的字符串
        string saveJsonStr = JsonMapper.ToJson(save);
        //将字符串写入文件中 先建立streamWrite
        StreamWriter sw=new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        sw.Close();
        UIManager._instance.ShowMessage("保存成功");

    }
    private void LoadByJson() 
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        if (File.Exists(filePath))
        {
            //创建一个streamReader,用来读取流
            StreamReader sr = new StreamReader(filePath);
            //将读取到的流赋值给jsonstr
            string jsonStr=sr.ReadToEnd();
            sr.Close();
            Save save = JsonMapper.ToObject<Save>(jsonStr);
            SetGame(save);
            UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
    }

    public void ContinueGame()
    {
    
        UnPause();
        UIManager._instance.ShowMessage("");
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UIManager._instance.ShowMessage("");

        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }

    //保存游戏
    public void SaveGame()
    {
        //SaveBybin();
        //SaveByJson();
        SaveByXml();
       
    }
    //加载游戏
    public void LoadGame()
    {
       // LoadBybin();
       LoadByJson();
    }
}

XML加载游戏

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

public class GameManager : MonoBehaviour
{
    public static GameManager _instance; 
    //1.设置暂停
    public bool isPaused = true;
    //2.获得组件
    public GameObject menuGo;
    //3.设置数组
    public GameObject[] targetGOs;
    private void Awake()
    {
        _instance = this;
        Pause();    
    }

    private void Update()
    {
        //判断是否按下esc键 是并暂停游戏
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Pause();
        }
    }

    private void Pause()
    {
        isPaused = true;
        menuGo.SetActive(true);
        Time.timeScale = 0;
        //隐藏鼠标图标
        Cursor.visible = true;
    }

    private void UnPause()
    {
        isPaused = false;
        menuGo.SetActive(false);
        Time.timeScale = 1;
        Cursor.visible=false;
    }

    //创建save对象并存储当前游戏状态
    private Save CreateSaveGO()
    {
        //新建save对象
        Save save = new Save();
        //遍历所有的target
        //如果其中有处于激活状态的怪物,就把该target的位置信息和激活状态的怪物的类型添加到List中
        foreach(GameObject targetGO in targetGOs)
        {
            TargetManager targetManager = targetGO.GetComponent<TargetManager>();
            if(targetManager.activeMonster != null) {
            save.livingTargetPositions.Add(targetManager.targetPosition);
                int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType;
                save.livingMonsterTypes.Add(type);
            }
        }
        //把shootNum和score保存在Save对象中
        save.shootNum = UIManager._instance.shootNum;
        save.score = UIManager._instance.score;
        //返回该Save对象
        return save;
    }


    //设置 通过读档信息重置界面
    private void SetGame(Save save)
    {
        //先将所有target里面的怪物清空 并重置所有的计时
        foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        //通过反序列化得到save对象中存储的信息,激活指定的怪物
        for(int i = 0; i < save.livingTargetPositions.Count; i++)
        {
            int position = save.livingTargetPositions[i];
            int type = save.livingMonsterTypes[i];

            targetGOs[position].GetComponent<TargetManager>().ActivateMonsterByType(type);
        }

        //更新UI显示
        UIManager._instance.shootNum = save.shootNum;
        UIManager._instance.score = save.score;

       
        UnPause();
    }


    //各种方法保存游戏 存档和读档
    private void SaveBybin()
    {//序列化的过程 将save对象转化为字节流
        Save save = CreateSaveGO();
        //创建二进制格式程序
        BinaryFormatter bf = new BinaryFormatter();
        //创建文件流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile"+"/byBin.txt");
        //用二进制格式化程序的序列化方法序列化save对象
        bf.Serialize(fileStream, save);
        //关闭流
        fileStream.Close();
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }

    private void LoadBybin()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            //反序列化过程
            //创建一个二进制格式化程序
            BinaryFormatter bf = new BinaryFormatter();
            //打开一个文件流
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
            //调用格式化程序的反序列化方法,将文件流转化为一个Save对象
            Save save = (Save)bf.Deserialize(fileStream);
            //关闭文件流
            fileStream.Close();

            SetGame(save);
        UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
       
    }

    private void SaveByXml()
    {
        Save save=CreateSaveGO();
        //存储路径
        string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
        //创建XML文档
        XmlDocument xmlDoc = new XmlDocument();
        //创建根节点
        XmlElement root = xmlDoc.CreateElement("save");
        //设置根节点的值
        root.SetAttribute("name", "saveFile1");
        //创建Xml元素
        XmlElement target;
        XmlElement targetPosition;
        XmlElement monsterType;
        //遍历save中存储的数据并转换成xml格式
        for(int i = 0;i<save.livingTargetPositions.Count;i++)
        {
            target = xmlDoc.CreateElement("target");
            targetPosition = xmlDoc.CreateElement("targetPosition");
            targetPosition.InnerText = save.livingTargetPositions[i].ToString();
            monsterType = xmlDoc.CreateElement("monsterType");
            monsterType.InnerText = save.livingMonsterTypes[i].ToString();
            //设置节点之间的层级关系
            target.AppendChild(targetPosition);
            target.AppendChild(monsterType);
            root.AppendChild(target);
        }
        //设置射击数和分数节点
        XmlElement shootNum = xmlDoc.CreateElement("shootNum");
        shootNum.InnerText = save.shootNum.ToString();
        XmlElement score = xmlDoc.CreateElement("score");
        score.InnerText = save.score.ToString();

        root.AppendChild(shootNum);
        root.AppendChild(score);

        xmlDoc.AppendChild(root);
        xmlDoc.Save(filePath);

        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byXML.txt"))
        {
            UIManager._instance.ShowMessage("保存成功");
        }
    }
    private void LoadByXml()
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
        if(File.Exists(filePath))
        {
            Save save = new Save();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);
            //通过节点名称来获取元素:结果为XmlNodeList类型
            XmlNodeList targets = xmlDoc.GetElementsByTagName("target");
            //遍历所有的target节点 并获取子节点和子节点的Innertext
            if(targets.Count !=0) {
            foreach(XmlNode target in targets){

                    XmlNode targetPosition = target.ChildNodes[0];
                    int targetPositionIndex=int.Parse(targetPosition.InnerText);
                    //把得到的值存储到save中
                    save.livingTargetPositions.Add(targetPositionIndex);

                    XmlNode monsterType = target.ChildNodes[1];
                    int monsterTypeIndex=int.Parse(monsterType.InnerText);
                    save.livingMonsterTypes.Add(monsterTypeIndex);
                }
            }
            //得到存储的射击数和分数
            XmlNodeList shootNum = xmlDoc.GetElementsByTagName("shootNum");
            int shootNumCount =int.Parse(shootNum[0].InnerText);
            save.shootNum = shootNumCount;
            XmlNodeList Score = xmlDoc.GetElementsByTagName("score");
            int scoreCount = int.Parse(Score[0].InnerText);
            save.score= scoreCount;

            SetGame(save);
            UIManager._instance.ShowMessage("");
        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不存在");
        }
    }
    private void SaveByJson()
    {
        Save save= CreateSaveGO();
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        //利用jsonmapper将save对象转换为json格式的字符串
        string saveJsonStr = JsonMapper.ToJson(save);
        //将字符串写入文件中 先建立streamWrite
        StreamWriter sw=new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        sw.Close();
        UIManager._instance.ShowMessage("保存成功");

    }
    private void LoadByJson() 
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        if (File.Exists(filePath))
        {
            //创建一个streamReader,用来读取流
            StreamReader sr = new StreamReader(filePath);
            //将读取到的流赋值给jsonstr
            string jsonStr=sr.ReadToEnd();
            sr.Close();
            Save save = JsonMapper.ToObject<Save>(jsonStr);
            SetGame(save);
            UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存档文件不在");
        }
    }

    public void ContinueGame()
    {
    
        UnPause();
        UIManager._instance.ShowMessage("");
    }

    public void NewGame()
    {
//3. 要更新9个位置的怪物 先设置数组
foreach(GameObject targetGO in targetGOs)
        {
            targetGO.GetComponent<TargetManager>().UpdateMonsters();
        }
        UIManager._instance.shootNum = 0;
        UIManager._instance.score = 0;
        UIManager._instance.ShowMessage("");

        UnPause();
    }
    //退出游戏
    public void QuitGame()
    {
        Application.Quit();
    }

    //保存游戏
    public void SaveGame()
    {
        //SaveBybin();
        //SaveByJson();
        SaveByXml();
       
    }
    //加载游戏
    public void LoadGame()
    {
       // LoadBybin();
      // LoadByJson();
      LoadByXml();
    }
}

本文作者:flyall

本文链接:https://www.cnblogs.com/flyall/p/17182423.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   flyall  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.