- Home /
How do you save an instance of a game object in Unity C# after exiting the game?
I'm trying to save my checkpoint controller which logs the last checkpoint position that the player collided with and in another script loads the player by the last touched checkpoint on death. The only issue that I have is when I exit the build altogether. I have a PlayerPrefs.GetInt setup that saves the last scene the player was in but not the last checkpoint position they were in. Any suggestions?
private static int currentScene
public void LoadMenu()
{
currentScene = SceneManager.GetActiveScene().buildIndex;
PlayerPrefs.SetInt("SavedScene", currentScene);
SceneManager.LoadScene(7);
}
Ignoring the main menu scene load. Is there any way to save the checkpoint controller's last logged position using the SetInt/String method?
Here's the checkpoint controller script:
private static CheckpointController instance;
public Vector3 previousCheckPointPos;
// Start is called before the first frame update
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(instance);
}
else
{
Destroy(gameObject);
}
}
Answer by rob11 · Oct 23, 2019 at 01:26 AM
Are the checkpoints always at same places ? If yes, I would save an Id through playprefs as an int. And when you want to load your character, you place it at the corresponding checkpoints position.
If these are moving or randomly placed checkpoints, I would divide the Vector3 position of the last checkpoint (or Vector2 if you're in 2D) into int variables. This time when you load, you recreate the vector with these variables to place your character at the right place.
For example :
public void SaveCheckpoint()
{
PlayerPrefs.SetInt("LastCheckPointXpos", currentCheckpoint.transform.position.x);
PlayerPrefs.SetInt("LastCheckPointYpos", currentCheckpoint.transform.position.y);
PlayerPrefs.SetInt("LastCheckPointZpos", currentCheckpoint.transform.position.z);
}
public void LoadPlayer()
{
player.transform.position = new Vector3(PlayerPrefs.GetInt("LastCheckPointXpos"), PlayerPrefs.GetInt("LastCheckPointYpos"), PlayerPrefs.GetInt("LastCheckPointZpos"));
}
But if you want to retrieve a specific Checkpoint for a list of checkpoints that are always the same, just save the index of the array and retrieve it at runtime. If they are randomly generated and you want to rebuild the entire object at runtime, you'll have to save all its variables and rebuild it through code. If you want to know more on the subject, you could read about data serialization, there's more efficient ways to save objects than always using playerprefs. Playerprefs are really handy when you need a couple variables but can get a little bit troublesome if you have too much.
Good luck!