2

I want to save the list of type Myclass in PlayerPrefs.

I saw an example with converting in a String, how can I do that?

public class MyClass{
     private int ex;
}
List<MyClass> l = new List<MyClass>();
//How to save it?
2
  • please include some code snippets so that your question can be easily understand.
    – Joseph
    Commented Nov 12, 2015 at 11:08
  • Note that there may be a string size limit for PlayerPrefs depending on the target platform. See this answer on Unity Answers - PlayPrefs Limitations
    – sonnyb
    Commented May 29, 2019 at 17:00

3 Answers 3

6

Approach using JSON to serialize/deserialize your object into string is the better option in my personal opinion.

You can find a lot of JSON libs for C#, just research for it and find one that suits better for you.

Or take a look at unity wiki ArrayPrefs2 and extends or use it to create your own parser to save your object structures. I, personally, wouldn't recommend this approach to save entire objects but is an option to mention...

When your object is simple enough to use JsonConverter from Newtonsoft as suggested by Povl Eller:

To Save

Character char = new Character();
char.Name = "Apple";
char.Level = 1;
char.Health = 150;
char.Attributes = new int[] { 10, 10, 10 };

PlayerPrefs.SetString( "PlayerCharacter", JsonConvert.SerializeObject(char) );

To Load

Character char = JsonConvert.DeserializeObject<Character>( PlayerPrefs.GetString( "PlayerCharacter" ) );

If you need to control the serialization for more complex objects or something you can use JsonSerializer that is documented in this same link at newtonsoft website.

OBS: I write this code directly here and didn't test it, probably you'll need to adjust it to be useful...

1
1

Perhaps something like

for(int i=0;i<list.length;i++)
{
    PlayerPrefs.SetString(list(i).name, list(i).value);
}
-3

Try to use newtonsoft.json.

They have extended examples and these two should get you started: http://www.newtonsoft.com/json/help/html/SerializeObject.htm http://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Best Regards

1
  • using just links is a bad practice for answer because links can become invalid and response useless
    – Frohlich
    Commented Nov 12, 2015 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.