K
K
KeysCG2021-10-06 01:46:03
Unity
KeysCG, 2021-10-06 01:46:03

How to make save lives separate on each level of PlayerPrefs?

Please help me solve the problem, I've been suffering with it all day and I just can't figure out how to do it!
There is a separate scene with a choice of levels (levels open as they pass):
615cd1e837350589728170.png
There is also a life script that hangs on the character:
615cd2027b206741377336.png
The transition from level to level occurs through a Trigger with a script:
615cd2ce77be9929924656.png
615cd2e5bf422857789788.png
I need to save lives so that when I get on the trigger it is saved information on the lives of this particular level (so that in the future, if you need to replay the level, the number of lives loaded is exactly the one that was saved when passing the previous level on the trigger)
As I understand it, you need to make a script on a trigger that will save lives in a separate registry key, for example, under the name SaveHealthLvl1, and already at the next level in a separate key SaveHealthLvl2, etc. and then, when choosing a level, it will load the desired key.

I beg you, please help me visually how to implement this through PlayerPrefs, otherwise I'm sitting all day and I can't find the info anywhere. Everywhere only how to save from level to level and when choosing a level, only the last number of lives is loaded :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Goppe Eugene, 2021-10-06
@EvgeniyGP

The first thing that came to mind. You can simply convert the level number to a string and add some prefix for readability, but this option is not very flexible.

String saveText = "HealthLvl";

void SaveLevelHP(int level, int hp)
{
    PlayerPrefs.setInt(saveText + level.toString(),hp)
}

int LoadLevelHP(int level)
{
   return PlayerPrefs.getInt(saveText + level.toString())
}

A more complex and more flexible option is to use JSON , which can be serialized to a string and stored in PlayerPrefs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question