Load and save file. IOS problem

Hey,

I want to migrate my Unity game into IOS system, but I have a problem with load and save file.This is simple file with player high score. It work fine for the android but crash on the IOS. This is my code:

using UnityEngine;
     using System.Collections;
     using UnityEngine.UI;
     using System.Runtime.Serialization.Formatters.Binary;
     using System.IO;
    
    
     public class GameMaster : MonoBehaviour {
    
         PlayerData playerData = new PlayerData();
    
           void Start () {
    
             LoadPlayerData ();
          }
    
         public void SavePlayerData()
         {
             if ( score > playerData.highScore) 
             {
                 BinaryFormatter bf = new BinaryFormatter ();
                 FileStream file = File.Create (Application.persistentDataPath
                                                         + "/playerInfo.dat");
    
                 playerData.highScore = score;
                 isHighScore = true;
    
                 bf.Serialize( file, playerData);
                 file.Close();
             }
         }
    
         public void LoadPlayerData()
         {
             //Debug.Log ("Application.persistentDataPath: " + Application.persistentDataPath);
             if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
             {
                 BinaryFormatter bf = new BinaryFormatter ();
                 FileStream file = File.Open( Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
    
                 playerData = (PlayerData)bf.Deserialize( file);
                 highScoreText.text = "High Score: " + playerData.highScore;
    
                 file.Close();
             }
         }
    
     }
    
    
     [System.Serializable]
     class PlayerData
     {
         public int highScore = 0;
     }

When I comment invoke of LoadPlayerData function in start() and SavePlayerData I don’t have any bugs or crash on my iPhone but ofc. I can’t load and save best score either. Do you know where is the problerm?

Thanks.

What does the xCode log say? Throw in some Debug.Log(); inside your SavePlayerData() function, and see how far it gets before crashing.

I put some Debug.log() into Unity code:

public void SavePlayerData()
    {
       
        if ( pkt > playerData.highScore)
        {
            Debug.Log( "save function");

            BinaryFormatter bf = new BinaryFormatter ();

            Debug.Log( "after Binary formatter");

            Debug.Log( Application.persistentDataPath);

            FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat");

            Debug.Log( "Created file");

            playerData.highScore = pkt;
            isHighScore = true;
       
            bf.Serialize( file, playerData);

            Debug.Log( "after Serialize");

            file.Close();
        }
    }

    public void LoadPlayerData()
    {
        //Debug.Log ("Application.persistentDataPath: " + Application.persistentDataPath);
        if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
        {
            Debug.Log( "Load function");

            BinaryFormatter bf = new BinaryFormatter ();

            Debug.Log( "after Binary formatter");

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

            Debug.Log( "file is open");

            playerData = (PlayerData)bf.Deserialize( file);

            Debug.Log( "after "Deserialize");

            highScoreText.text = "Best score: " + playerData.highScore;
       
            file.Close();
        }
    }

I got this xCode debug log:

Load function


(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 65)


after Binary formatter


(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 65)


file is open


(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 65)


SerializationException: Unexpected binary element: 255

  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info) [0x00000] in <filename unknown>:0

  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadNextObject (BinaryElement element, System.IO.BinaryReader reader) [0x00000] in <filename unknown>:0

  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectGraph (BinaryElement elem, System.IO.BinaryReader reader, Boolean readHeaders, System.Object& result, System.Runtime.Remoting.Messaging.Header[]& headers) [0x00000] in <filename unknown>:0

  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) [0x00000] in <filename unknown>:0

  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize (System.IO.Stream serializationStream) [0x00000] in <filename unknown>:0

  at GameMaster.LoadPlayerData () [0x00000] in <filename unknown>:0

  at GameMaster.Start () [0x00000] in <filename unknown>:0


(Filename:  Line: -1)


save function


(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 65)


after Binary formatter


(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 65)


/var/mobile/Containers/Data/Application/2BB9F0C8-DB09-47C7-995D-B679BB45AC0F/Documents


(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 65)


IOException: Sharing violation on path /var/mobile/Containers/Data/Application/2BB9F0C8-DB09-47C7-995D-B679BB45AC0F/Documents/playerInfo.dat

  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0

  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) [0x00000] in <filename unknown>:0

  at System.IO.File.Create (System.String path, Int32 bufferSize) [0x00000] in <filename unknown>:0

  at System.IO.File.Create (System.String path) [0x00000] in <filename unknown>:0

  at GameMaster.SavePlayerData () [0x00000] in <filename unknown>:0

  at GameMaster.przegranaGra () [0x00000] in <filename unknown>:0

  at CoinCatcher.OnTriggerEnter2D (UnityEngine.Collider2D other) [0x00000] in <filename unknown>:0


(Filename:  Line: -1)

EDIT:
I found similar problem with ‘SerializationException: Unexpected binary element: 255’
http://answers.unity3d.com/questions/759895/why-has-my-binaryformatter-stopped-working.html?sort=oldest

I added:

void Awake()
    {
        // Forces a different code path in the BinaryFormatter that doesn't rely on run-time code generation (which would break on iOS).
        Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
    }

into file when I have LoadPlayerData() and SavePlayerData()
Plus I deleted old version of my app form the iPhone before I compile new one in xCode.
Looks fine now. I can save and load high score and it doesn’t crash.

hmmm I tested it once again and I have still problem with this. With first run everything works fine but after few restarts problem comes back