Advertisement

Save and load scene in unity

Started by December 05, 2016 09:02 AM
3 comments, last by Robin90 8 years ago

i writing my code for the save game progress, i able to save my player position and player score and health. I want my save game load from the main menu. Anyone can help me? i got 4 scene which is 1 main menu and 3 level.

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class SaveandLoadScript : MonoBehaviour {
public Transform player;
public Transform enemy;
public int score = 0;
public int[] SceneID =new int[]{'0','1','2','3'};
public void save()
{
PlayerPrefs.SetInt("Score",score);
PlayerPrefs.SetFloat("PlayerPosX", player.position.x);
PlayerPrefs.SetFloat("PlayerPosY", player.position.y);
PlayerPrefs.SetFloat("PlayerPosZ", player.position.z);
PlayerPrefs.SetFloat("EnemyPosX", enemy.position.x);
PlayerPrefs.SetFloat("EnemyPosY", enemy.position.y);
PlayerPrefs.SetFloat("EnemyPosZ", enemy.position.z);
PlayerPrefs.SetInt("SceneID", SceneManager.GetActiveScene().buildIndex);
PlayerPrefs.Save();
}
public void Load()
{
PlayerPrefs.GetInt("Score", 0);
PlayerPrefs.GetInt("SceneID", SceneManager.GetActiveScene().buildIndex);
player.position = new Vector3(PlayerPrefs.GetFloat("PlayerPosX"), PlayerPrefs.GetFloat("PlayerPosY"), PlayerPrefs.GetFloat("PlayerPosZ"));
enemy.position = new Vector3(PlayerPrefs.GetFloat("PlayerPosX"), PlayerPrefs.GetFloat("PlayerPosY"), PlayerPrefs.GetFloat("PlayerPosZ"));
}
}

Don't forget to call PlayerPrefs.Save(). I've definitely done that a few times.

Advertisement

i added this into my save function, but the problem is i cannot load my game in the main menu...and another problem is with this code i no able to save many enemies. it just save one enemy, can you help me with that?

For Finding multiple enemies, I hope you tagged them as "Enemy", or something similar to that, with that in mind:

(Oh, according to Unity you need to write an abstraction Layer to PlayerPrefs to save multiple so think about doing it as a peasant)

  1. foreach(GameObject ObjectToSave in GameObject.FindGameObjectsWithTag("Enemy"))
  2. {
  3. StreamWriter sw = new StreamWriter(@"SaveFile.s");
  4. sw.WriteLine(ObjectToSave.Name + " - " + ObjectToSave.transform.Location.X + " - " + ObjectToSave.transform.Location.Y +
  5. " - " + ObjectToSave.transform.Location.Z + " - " + ObjectToSave.transform.Quaternion.eulerAngles);
  6. }
  7. sw.Close();

Add StreamReader to read the save file from main menu, lets say Line one to point the scene and set bool Load for instance for scene Main Controllers cript to know to read the rest of the file, then just do the same thing you did for saving only in reverse to return everything the way it was in the scene.

Or run it like XML file that is a lot more elegant.

I had the same issue.

This topic is closed to new replies.

Advertisement