Search code examples
c#unity-game-engineblackjack

Working on a blackjack style unity game. Can't read and write a file


So. I'm trying to make a save profile but I have the error shown in the picture and have no idea how to fix it as I have been following tutorials on YouTube and this error never occurred. Can anyone help me work out what I should do.

enter image description here

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

public class SavingControl : MonoBehaviour
{
    public static SavingControl control;

    public int cash = PlayerBetting.instance.bankBal;
    public int difficulty = 2;

    void Awake ()
    {
        if (control = null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }
        else if (control != this)
        {
            Destroy(gameObject);
        }        
    }

    public void Save()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");

        PlayerData data = new PlayerData();
        data.BankBal = cash;
        data.Difficulty = difficulty;

        bf.Serialize(file, data);
        file.Close();    
    }

    public void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/PlayerInfo.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath = "/PlayerInfro.dat", FileMode.Open);
            PlayerData data = (PlayerData)bf.Deserialize(file);
            file.Close();

            cash = data.BankBal;
            difficulty = data.Difficulty;
        }
    }    
}


[Serializable]
class PlayerData
{
    public int BankBal;
    public int Difficulty;
}

Solution

  • Change the = to a +:

    FileStream file = File.Open(Application.persistentDataPath + "/PlayerInfro.dat", FileMode.Open);
    

    Better yet use Path.Combine:

    FileStream file = File.Open(Path.Combine(Application.persistentDataPath, "PlayerInfro.dat"), FileMode.Open);