I'm trying to build a game for Android just like Minecraft using Unity. How can I save my progress?
I'm trying this code but I'm still clueless if I'm on the right track.
public class SavePref : MonoBehaviour {
GameObject[] objects;
float x;
float y;
float z;
// Use this for initialization
void Start () {
objects = GameObject.FindGameObjectsWithTag("ObjectSnap");
}
// Update is called once per frame
void Update () {
}
public void Load()
{
foreach (GameObject obj in objects)
{
obj.name = PlayerPrefs.GetString("Ojects");
x = PlayerPrefs.GetFloat("X");
y = PlayerPrefs.GetFloat("Y");
z = PlayerPrefs.GetFloat("Z");
}
}
public void Save()
{
objects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
Debug.Log(objects.Length);
foreach (GameObject obj in objects)
{
PlayerPrefs.SetString("Objects", obj.name);
Debug.Log(obj.name);
x = obj.transform.position.x;
PlayerPrefs.SetFloat("X", x);
y = obj.transform.position.y;
PlayerPrefs.SetFloat("Y", y);
z = obj.transform.position.z;
PlayerPrefs.SetFloat("Z", z);
Debug.Log(obj.transform.position.x);
Debug.Log(obj.transform.position.y);
Debug.Log(obj.transform.position.z);
}
}
}
The reason is you are overwriting the same values.
Every object in the scene will overwrite the same 'X' 'Y' 'Z' and 'Objects' variables of PlayerPerfs. So, if you want to save just blocks positions,
each block in the scene has to have its own sceneID.
When you write the PlayerPerfs, use these IDs.
For example:
This code will just save blocks positions, and will recreate the world with white cubes.
If you want to save the type of blocks, you should have all types of blocks as prefarbs, and instantiate prefabs, when Load().
P.S. Anyway, such realisation of Minecraft clone for Android is terrible. Imagine, you have one little chunk (32*32*32) full of blocks, then the RAM will have to handle 32768 blocks in memory (which just kill the application).
So, you have to operate not blocks, but the sides of these blocks, to cull the sides, which aren't visible.
And you shouldn't save the scene information via PlayerPerfs. Use System.IO instead. As i know, PlayerPerfs, saves information in registry, which isn't good for such data.