unity3d - 无法隐式转换类型,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”
我正在为这些错误寻找解决方案。我不知道如何解决这些。
有人来帮帮我吗???
解决方案
HighScore data = formatter.Deserialize(stream) as SaveHighScore;
您正在反序列化 aSaveHighScore
但试图将其保存在 a 中HighScore
,这是一个 MonoBehaviour 组件,与您希望的完全不同。
将您的代码修改为
var data = formatter.Deserialize(stream) as SaveHighScore;
我认为一切都应该工作。
推荐阅读
- vpn - 在我的组织中使用多个站点到站点的最佳方式是什么
- selenium - Selenium-wire 响应对象 - 将响应主体作为字符串而不是字节获取的方法
- java - 我想通过蓝牙将数据从 Android 发送到 Arduino
- javascript - 通过添加 cookie 进行 CSS 样式表切换
- r - 如何解决 UseMethod() 中的此错误?
- qt - Qt/QML - 如何自定义 Popup 调光效果?
- java - org.jasypt.exceptions.EncryptionOperationNotPossibleException 抛出 HTTP 状态 500
- kotlin - 无法构建/运行 Jetpack Compose Multiplatform 的桌面版本,即使在最新版本的 IntelliJ 上的全新项目上也是如此
- java - 如何从代码的另一部分中的公共 ClassName 访问数据?
- javascript - WkWebview javascript动画在屏幕锁定时冻结