- Home /
Other
PlayerPrefs string to load scene (edited)
How can I uses PlayerPrefs to load a scene? My script looks like this:
using UnityEngine;
using System.Collections;
public class LoadandSaveManager : MonoBehaviour {
public string thisScene;
public void SaveGame(){
PlayerPrefs.SetString (thisScene, "0");
Debug.Log ("Saved");
}
public void LoadGame(){
Application.LoadLevel (PlayerPrefs.GetString (thisScene));
}
}
I feel like its a really simple fix, but I can't figure out how to do it, so if anyone could tell me how to, it would be very helpful.
Thanks!
Answer by Cynikal · Oct 26, 2016 at 01:32 AM
Application.LoadLevel(PlayerPrefs.GetString("WhatScene"));
That SHOULD work... However...
You should also make sure it's not null..
if (!String.IsNullOrWhiteSpace(PlayerPrefs.GetString("whatScene")))
{
Application.LoadLevel(PlayerPrefs.GetString("whatScene"));
} else {
Debug.LogError("Something is not right...");
}
Thank you so much for your quick response. I have a couple questions, though. Right now I have two scripts, one for the load game and one for the save game. Is that how I should go about it? Or is there a better way? Second, my plan was to have whatScene to be a variable so I would only need one script and I could use it throughout all my game. Is this possible? If so, how would I do it? Once again, thank you so much, and I hope I'm not being too confusing.
Simple answer: Yes.
There is almost never a difference in breaking stuff up into smaller files, or implementing it all in one file. So, you can have the save stuff in one file, and the load stuff in another.
Since "whatScene" is a variable, you could write directly to the playerprefs and pull it at will, or have a gamemanager script to pull the info from it as well.
I can't tell you if it's the right way of going about it, since I literally know nothing about your game, other than you're wanting to load a level based off of a variable.
Do what works. If it works.. Don't question it, until you start seeing reasons to.
I know I'm being a bit annoying, and I apologize for that, but I can't seem to be able to check if one button is pressed from a script. I know you can use OnButtonUp , but I'm not sure how to check if another button is being pressed without splitting it into another script. Again, sorry for all the questions, but I am fairly new to Unity, so I'm still trying to get a grasp on things.
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Simple networking - Sending string over network? 1 Answer
Replace the first string C# 1 Answer
Text isn't showing up on button 0 Answers