首页 > 解决方案 > 无法隐式转换类型,UNITY

问题描述

我将制作一个保存系统来保存我的统一游戏中的高分,但给了我两个错误,这是第一个数据代码,,,

public class SaveHighScore
{
    public int highScore;

    public SaveHighScore(HighScore highscore)
    {
        highScore = highscore.highScore;
    }
}

这是我第二次保存系统

public class SaveSystem
{
     public static void SaveScore(HighScore highscore)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            string path = Application.persistentDataPath + "/player.fun";
            FileStream stream = new FileStream(path, FileMode.Create);

            SaveHighScore data = new SaveHighScore(highscore);
            formatter.Serialize(stream, data);
            stream.Close();
        }
        public static SaveHighScore loadHighScore()
        {
            string path = Application.persistentDataPath + "/player.fun";
            if (File.Exists(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream stream = new FileStream(path, FileMode.Open);
                HighScore data = formatter.Deserialize(stream) as SaveHighScore;
                stream.Close();
                return (SaveHighScore) data;
            }
            else
            {
                Debug.Log("no highScore found");
                return null;
            }
}

这是我的第三个也是最后一个代码

public class HighScore : MonoBehaviour
{
    public int highScore;
    public void saveHighscore()
    {
        SaveSystem.SaveScore(this);
    }
    public void loadHighscore()
    {
        SaveHighScore data = SaveSystem.loadHighScore();
        highScore = data.highScore;
    }
}

第一个代码是准备要保存的数据。第二个代码是制作保存系统。第三个是当玩家想要加载最后一个高分时调用两个函数。

但在第二个代码中有两个错误。

SaveSystem.cs(24,30) 无法将类型“SaveHighScore”隐式转换为“HighScore”

SaveSystem.cs(26,20) 无法将类型“HighScore”隐式转换为“SaveHighScore”

我正在为这些错误寻找解决方案。我不知道如何解决这些。

有人来帮帮我吗???

标签: unity3d

解决方案


HighScore data = formatter.Deserialize(stream) as SaveHighScore;

您正在反序列化 aSaveHighScore但试图将其保存在 a 中HighScore,这是一个 MonoBehaviour 组件,与您希望的完全不同。

将您的代码修改为

var data = formatter.Deserialize(stream) as SaveHighScore;

我认为一切都应该工作。


推荐阅读