ISaveable and saving some simple ints

Greetings,
I have a question. I want to save some ints from within a script. Is there an easier way than trying to put them into a List and then extract them? It seems a bit odd to use a List for a specific amount of int variables.
Thank you!

How do you have those ints stored?

There are several ways to save a collection of int variables.
We’ll start with the one you’ve already mentioned. (Note that I don’t have the names of the int variables you will be saving, so I’m going very generic with this).

int a;
int b;
int c;

public object CaptureState()
{
    List<int> state = new List<int>();
    state.Add(a);
    state.Add(b);
    state.Add(c);
    return state;
}
public void RestoreState(object state)
{
    List stateList = (List<int>)state;
    a=stateList[0];
    b=stateList[1];
    c=stateList[2];
}

You could also create a Dictionary, naming the references

public object CaptureState()
{
    Dictionary<string, int> state = new Dictionary<string, int>();
    state["a"] = a;
    state["b"] = b;
    state["c"] = c;
    return state;
}
public void RestoreState(object state)
{
    Dictionary<string, int> stateDict = (Dictionary<string, int>)state;
    a=stateDict["a"];
    b=stateDict["b"];
    c=stateDict["c"];  
}

and finally a custom data struct

[System.Serializeable] 
struct SavingStruct
{
     public int a;
     public int b;
     public int c;
}

public object CaptureState()
{
    SavingStruct state = new SavingStruct();
    state.a = a;
    state.b = b;
    state.c = c;
    return state;
}
public void RestoreState(object state)
{
    SavingStruct stateStruct = (SavingStruct)state;
    a = stateStruct.a;
    b = stateStruct.b;
    c = stateStruct.c;
}
1 Like

So it’s either a list/ dictionary or a struct. That helps a lot. Thank you Brian.
I also noticed the update on the Saving System you did last summer. As soon as i finish will also implement it on my project. Awesome work.

Note that with my Json saving system, you will have to choose the Dictionary option (well, a version of it called a JObject which is mapped to an IDictionary).

Good to know. Thanks again.
Structs also work, right?

With the Json saving system, structs can be problematic. They will always work perfectly in the Editor, and on games built using CLR, but as soon as you build to IL2CPP (which is pretty much what you WANT in a built game for distribution!), the linker may or may not STRIP the code for the struct. This is a known issue, although there are some workarounds, mostly involving using that struct outside of the saving system in a known guaranteed Unity callback… i.e. tricking Unity into thinking that the struct is useful.

Although I don’t do this for commercial purposes (it is for research purposes) I searched about what you said and saw the issue. Will have to think about it. Thanks again.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.