What I have:
I’m creating a World Builder.
With each World, I’ll need to save multiple variables associated with it.
Since PlayerPrefs don’t Get or Set arrays, I’ve coded a function to do that.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GeneratorTools
{
public class Data : MonoBehaviour
{
public void Save(string FileType, string FileName, int[] IntArrayToSave, string[] StringArrayToSave)
{
PlayerPrefs.SetString(FileType + "-" + FileName + "-Name-", FileName);
for (int i = 0; i < StringArrayToSave.Length; i++)
{
PlayerPrefs.SetString(FileType + "-" + FileName + "-Info-" + i, StringArrayToSave[i]);
}
for (int i = 0; i < IntArrayToSave.Length; i++)
{
PlayerPrefs.SetInt(FileType + "-" + FileName + "-Data-" + i, IntArrayToSave[i]);
}
}
public void Load(string FileType, string FileName, out string WorldName, out int[] WorldData, out string[] WorldInfo)
{
int ArraySize = 0;
for (int i = 0; PlayerPrefs.HasKey(FileType + "-" + FileName + "-Data-" + i); i++)
{
ArraySize++;
}
if (ArraySize == 0)
{
Debug.LogError("File doesn't exist.");
WorldName = "Mundo Muito Genérico";
WorldData = new int[3] { 2, 2, 2 };
WorldInfo = new string[3] { "Médio", "Médio", "Moderada" };
return;
}
WorldName = PlayerPrefs.GetString(FileType + "-" + FileName + "-Name-");
WorldData = new int[ArraySize];
WorldInfo = new string[ArraySize];
for (int i = 0; i < ArraySize; i++)
{
WorldData[i] = PlayerPrefs.GetInt(FileType + "-" + FileName + "-Data-" + i);
WorldInfo[i] = PlayerPrefs.GetString(FileType + "-" + FileName + "-Info-" + i);
}
}
}
}
What I need:
A list of all Keys that start with a specific FileType, so I can populate a Scroll View and make a “list of save files”.
Another possible problem:
I’m not quite sure, but it seems counter-intuitive to save multiple things associated with the same element under many different keys.
In the above code, I’d have, for example:
WORLD-GenericWorld-Name
WORLD-GenericWorld-Data-0
WORLD-GenericWorld-Data-1
WORLD-GenericWorld-Data-2
WORLD-GenericWorld-Info-0
WORLD-GenericWorld-Info-1
WORLD-GenericWorld-Info-2
All associated with “Generic World”.
Possible solution:
It’d seem way more intuitive to me, and possibly more optimized, to have all of this under one single file named “GenericWorld”, with its Name on a line, Data on another line (with 0, 1 and 2 separated by commas), and Info on another line (separated by commas as well).
How can I do that?
Which file type/structure should I use to save this data?
This app will run mainly on Android and iOS, so I need something that works on both.
Should I use XML? Maybe JSON?
If so, can you point me to a tutorial on how to save/load data using the recommended file structure?