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"
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();
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.
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?".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.