[英]How do i prevent the CS0161 error? - unity
i am using unity 2018. I want to save my data in my game but i keep getting the error: "Assets/Assets/Scripts/SaveSystem.cs(15,30): error CS0161: `SaveSystem.LoadPlayer()': not all code paths return a value"我正在使用 unity 2018。我想将我的数据保存在我的游戏中,但我不断收到错误消息:“资产/资产/脚本/SaveSystem.cs(15,30):错误 CS0161:`SaveSystem.LoadPlayer()':不是所有代码路径都返回一个值”
This is the current code im using:这是我使用的当前代码:
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem {
public static void SavePlayer(GlobalCookies player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "playerdata.bcdata";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + "playerdata.bcdata";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file 'playerdata.bcdata' was not found, please reinstall the missing file (error in: " + path + ")");
}
}
}
Under your Debug.LogError
call, add throw new InvalidOperationException();
在您的
Debug.LogError
调用下,添加throw new InvalidOperationException();
Like so:像这样:
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + "playerdata.bcdata";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
String message = "Save file 'playerdata.bcdata' was not found, please reinstall the missing file (error in: " + path + ")";
Debug.LogError( message );
throw new InvalidOperationException( message );
}
}
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + "playerdata.bcdata";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file 'playerdata.bcdata' was not found, please reinstall the missing file (error in: " + path + ")");
return null;
}
}
Not all paths returns a value error happens because your function expects a return value.并非所有路径都会发生返回值错误,因为您的函数需要返回值。 You are returning data on "if" part but not on "else" part of function.
您正在返回“if”部分的数据,而不是函数的“else”部分的数据。
It's like it's asking you "Okay I am returning data to you if I found it but what if I couldn't find it?".这就像在问你“好吧,如果我找到了数据,我会把数据还给你,但如果我找不到怎么办?”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.