- Home /
Can you load a level through using PlayerPrefs?
Hello I have run into a small problem with my level loading. The game is a small 2D game where when you hit a trigger you lose the game and it opens a new scene where it says "try again". When you press "Try Again" I want to be able to load the last played level. I tried using player prefs so I did this:
"PlayerPrefs.SetString = Application.loadedLevelName;"
And then tried to call it in a different script with this line:
"Application.LoadLevel (PlayerPrefs.GetString);"
but unity didn't like it and i got an error message. I just need a way to load the last played level when you press a button. Any and all help is much appriciated.
Answer by Bunny83 · Aug 21, 2015 at 11:41 AM
Well, to store a string in PlayerPrefs you have to provide a "name" for the value you want to save. That name you have to use when you want to read the value back:
// storing the current level
PlayerPrefs.SetString("lastLevel", Application.loadedLevelName);
// loading the stored level or if none was stored yet, the "defaultLevelName".
Application.LoadLevel(PlayerPrefs.GetString("lastLevel", "defaultLevelName"));
Thank you all for the help, works perfectly now. All I had to do was use PlayerPrefs correctly
Answer by Positive7 · Aug 21, 2015 at 12:06 AM
SetString() : http://docs.unity3d.com/ScriptReference/PlayerPrefs.SetString.html
GetString() : http://docs.unity3d.com/ScriptReference/PlayerPrefs.GetString.html
PlayerPrefs.SetString(Application.loadedLevelName, Application.loadedLevelName);
Application.LoadLevel(PlayerPrefs.GetString(Application.loadedLevelName));
A much easier way is using : http://docs.unity3d.com/ScriptReference/Application-loadedLevel.html
Application.LoadLevel(Application.loadedLevel);
Yes I know but the problem is when you lose in a certain level a lose screen comes up where you press try again and I want to be able to load the last played level not a specific one every time. So regardless of which level or scene you lost in you load that level.
So loading the current level wont work it has to be the last played level.
@Positive7: sorry, but i can't upvote your answer at the moment as your code makes no sense at all. Are you sure you understand PlayerPrefs yourself? ^^
Ohh, so "Try Again" is in a new scene.Then loadedLevel won't work for you, Sorry about that. But the SetString() GetString() should work.
@Bunny83 Yeah, I realized it's not setup correctly(after seeing your answer). It's my mistake, Sorry about that too. In my defence it works in a single scene tho. :D