简体   繁体   English

当级别结束时,如何将级别的分数添加到该级别之外的货币?

[英]How can I add a score from a level to a currency outside of said level when the level ends?

I have an int variable called "Stash".我有一个名为“Stash”的 int 变量。 When I beat the level, the game will save.当我通关时,游戏将保存。 When it saves, I want Stash goes up by however much my score was that level.当它保存时,无论我的分数是那个水平,我都希望 Stash 上升。 Currently, my code isn't saving my stash value, and it just sets it to "0(stash default) + Score(whatever my score was that level)."目前,我的代码没有保存我的 stash 值,它只是将它设置为“0(stash 默认)+ Score(无论我的分数是那个级别)”。 How can I write within this code to make my goal happen?我如何在此代码中编写以实现我的目标?

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

[RequireComponent(typeof(GameData))]
public class SaveScript : MonoBehaviour
{
    private GameData gameData;
    private string savePath;

    void Start()
    {
        gameData = GetComponent<GameData>();
        savePath = Application.persistentDataPath + "/gamesave.save";
    }

    public void SaveData()
    {
        var save = new Save()
        {
            SavedStash = gameData.Stash + gameData.Score      //<------ (This code)
        };

        var binaryFormatter = new BinaryFormatter();
        using (var fileStream = File.Create(savePath))
        {
            binaryFormatter.Serialize(fileStream, save);
        }

        Debug.Log("Data Saved");
    }

    public void LoadData()
    {
        if (File.Exists(savePath))
        {
            Save save;

            var binaryFormatter = new BinaryFormatter();
            using (var fileStream = File.Open(savePath, FileMode.Open))
            {
                save = (Save)binaryFormatter.Deserialize(fileStream);
            }
            gameData.Stash = save.SavedStash;              //<---------- (and this code)
            gameData.ShowData();

            Debug.Log("Data Loaded");
        }
        else
        {
            Debug.LogWarning("Save file doesn't exist");
        }
    }
}

Also relevant stuff in my GameData file:我的 GameData 文件中还有相关内容:

    public int Stash { get; set; }
    public int StashNew { get; set; }
    public int Score { get; set; }

The StashNew was just an idea I had to get the whole thing working. StashNew 只是我必须让整个事情工作的一个想法。

First of all: Never simply use + "/" for system file paths!首先:永远不要简单地使用+ "/"作为系统文件路径!

Different target devices might have different file systems with different path separators.不同的目标设备可能具有具有不同路径分隔符的不同文件系统。

Rather use Path.Combine which automatically inserts the correct path separators depending on the OS it is running on.而是使用Path.Combine ,它会根据运行的操作系统自动插入正确的路径分隔符。

savePath = Path.combine(Application.persistentDataPath, "gamesave.save");

Then to the main issue:然后是主要问题:

Properties like属性如

public int Stash { get; set; }
public int StashNew { get; set; }
public int Score { get; set; }

are not de-/serialized by the BinaryFormatter !不会BinaryFormatter /序列化

Therefore when you do因此当你做

binaryFormatter.Serialize(fileStream, save);

the numbers are not even written to the output file!数字甚至没有写入输出文件!

Then when reading in the same thing doesn't work and your properties simply keep the int default value of 0 .然后,当读取相同的内容不起作用并且您的属性只是保持int默认值0


Simply remove these { get; set; }只需删除这些{ get; set; } { get; set; } { get; set; } in order to convert your properties into serializable Fields and you should be fine. { get; set; }为了你的财产转化为可序列化字段,你应该罚款。

public int Stash;
public int StashNew;
public int Score;

Just for the demo I used this code仅用于演示我使用此代码

public class MonoBehaviourForTests : MonoBehaviour
{
    [SerializeField] private GameData In;
    [SerializeField] private GameData Out;

    [ContextMenu("Test")]
    private void Test()
    {
        var formatter = new BinaryFormatter();

        using (var fs = File.Open(Path.Combine(Application.streamingAssetsPath, "Example.txt"), FileMode.OpenOrCreate, FileAccess.Write))
        {
            formatter.Serialize(fs, In);
        }

        using (var fs = File.Open(Path.Combine(Application.streamingAssetsPath, "Example.txt"), FileMode.Open, FileAccess.Read))
        {
            Out = (GameData)formatter.Deserialize(fs);
        }
    }

    [Serializable]
    private class GameData
    {
        public int Stash;
        public int StashNew;
        public int Score;
    }
}

As you can see this has also the side-efect that now the fields actually appear in the Inspector and can be edited.正如您所看到的,这也有副作用,即现在这些字段实际上出现在 Inspector 中并且可以进行编辑。 I write values only to the In instance and after hitting Test you can see them loaded into the Out instance via the file.我只将值写入In实例,在点击Test后,您可以看到它们通过文件加载到Out实例中。

在此处输入图片说明


However in general I wouldn't recommend to use the BinaryFormatter here at all ... it adds a lot of overhead garbage you don't need at all.但是总的来说,我根本不建议在这里使用BinaryFormatter ......它增加了很多你根本不需要的开销垃圾。 Simply go for eg JSON or a comparable simple file format like XML or CSV which only store the relevant data.只需选择JSON或类似的简单文件格式,如 XML 或 CSV,它们只存储相关数据。

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

相关问题 我如何在Google Play服务中添加具有高水平和高得分的排行榜 - how can i add a single leaderboard with level and high score in google play services 使用 C# 9 顶级语句时,如何在 Main 的 scope 之外添加代码? - How do I add code outside the scope of Main when using C# 9 Top Level Statements? 如何添加一个 int 级别变量来决定从哪个级别开始获取对象? 我应该向它们添加哪些对撞机? - How can I add a int level variable to decide from what level to start getting the objects? And what colliders should I add to them? 如何在对话上方的顶层添加对话? - How can I add a Conversations on top level above the Dialogues? 如何确定深度级别如何将子节点添加到树视图? - How can I add child nodes to a treeview with deciding the depth level? 如何为每个级别只给一次分数? - How to give score only once for each level? 如何从 wpf 中的高级数据上下文获取数据上下文 - How can I get datacontext from hight level datacontext in wpf 如何从指定级别获取json节点? - How can i get a json node from a specified level? 如何从应用程序级别使用Azure中的服务配置? - How can I use service configuration in Azure from application level? 如何从后面的代码更改页面的缩放级别? - How can I change the zoom level of a page from code behind?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM