Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by FilouB · Sep 26, 2014 at 02:49 PM · webplayerbinaryformatterdeserialization

[C#] Deserialization fails in Web Player

I store serialized data in PlayerPrefs in the Web Player. In the UNITY IDE all works fine, but deserialization fails in the Web Player.

This is my code for the serializer and the serializable class.

 public class PlayerPrefsSerializer{
         
     public static BinaryFormatter bf=new BinaryFormatter();
             
     public static void Save(string key, object serializableObject){
         if(serializableObject==null) return;
         Debug.Log (string.Format ("Saving: {0} => {1}", key, serializableObject.GetType ()));
         MemoryStream memoryStream=new MemoryStream();
         bf.Serialize(memoryStream,serializableObject);
         string serializedData=System.Convert.ToBase64String(memoryStream.ToArray());
         PlayerPrefs.SetString(key, serializedData);
         Debug.Log (string.Format ("Saved serialized data {0}", serializedData));
         }
             
         public static object Load(string key){
             if(!PlayerPrefs.HasKey(key)){
                 Debug.Log ("Key not found");
                 return null;
             }
             string serializedData=PlayerPrefs.GetString(key,string.Empty);
             if(serializedData==string.Empty){
                 Debug.Log ("No data for providad key");
                 return null;
             }
             
             Debug.Log (string.Format ("Loading serialized data {0} {1}", key, serializedData));
             MemoryStream memoryStream=new MemoryStream(System.Convert.FromBase64String(serializedData));
             object returnObject=bf.Deserialize(memoryStream) as List<PlayerData>;
             Debug.Log (string.Format ("Loaded: {0} => {1}", key, returnObject.GetType ()));   
             //return null;
             return returnObject;
      }    
 }
 
 
 [Serializable]
 class PlayerData{        
    public int avatar{get;set;}
    public string playerName{get;set;}
    public PlayerData(int av, string pl){
         avatar=av;
         playerName=pl;
    }
 }

As mentioned above all works well in the UNITY IDE, but in the web player I get the following eror:

 [Log] : Loading serialized data player
 [Error] : Loading of Player information failed. Reason: System.MethodAccessException: Attempt to access a private/protected method failed.
   at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (object,object[],System.Exception&)
   at System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0 

This means the player data is being loaded (I dont post that data here), but deserialization fails. (I think in line 28) Does anyone know why? Does it have to do with Unity Security issues regarding the Web Player?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by FilouB · Sep 29, 2014 at 05:17 PM

Ok I solved the issue myself...

As the code broke in line 28 during deserialization I now serialize and deserialize using Json.NET. I also encode and decode the string as base64 to make it harder to mess with the PlayerPrefs file.

Serialization now works like this:

 public static void Save(){
     JsonSerializer serializer=new JsonSerializer();
     serializer.NullValueHandling=NullValueHandling.Ignore;
     StringWriter sw=new StringWriter();
     using(JsonWriter writer=new JsonTextWriter(sw)){
         writer.WriteStartObject();
         
         writer.WritePropertyName("Players");
         writer.WriteStartArray();
         foreach(PlayerDetails player in players) SavePlayer(writer,player);
         writer.WriteEndArray();
         
         writer.WriteEndObject();
     }
     sw.Close();
     StringBuilder bu = sw.GetStringBuilder();
     string entiredata = bu.ToString();
     string encodedData=EncodeTo64(entiredata);
     PlayerPrefs.SetString("SaveGame", encodedData);
 }

and deserialization like this:

 public static void Load(){
     players.Clear();
     
     if(!PlayerPrefs.HasKey("SaveGame")){
         return;
     }
     string encodedData=PlayerPrefs.GetString("SaveGame",string.Empty);
     if(encodedData==string.Empty){
         return;
     }
     Debug.Log ("Encoded savegame data from Playerprefs: "+encodedData);
     string serializedData=DecodeFrom64(encodedData);
     Debug.Log ("Decoded serialized savegame data from Playerprefs: "+serializedData);
     if(serializedData!=null){
         //parse content
         using (JsonTextReader reader=new JsonTextReader(new StringReader(serializedData))){
             while (reader.Read()){
                 if(reader.Value!=null){
                     if(reader.TokenType==JsonToken.PropertyName){
                         if((string)reader.Value=="Players")LoadPlayers(reader);
                     }
                 }
             }
         }
     }
 }

This works for me, as well in web player.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

EndOfStreamException : Failed to read past end of stream 1 Answer

Why does deserialization fail in the web player 1 Answer

UnityWebRequest deserialize content 0 Answers

EndOfStreamException : Failed to read past end of stream 1 Answer

Using BinaryFormatter for deserialization - ArgumentException: method argument length mismatch 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges