- Home /
playerprefs currency help
I am trying to use player prefs in my game to save a coin value when the level is won so it keeps the coin value into the next scenes by updating the ui text and adding the value 50 if the level is won! i have created a coin manager script which i have attached to each scenes ui text component and calling the funtions in my endgameroutine where i add value of 50 if the level is won and also in the startgameroutine! im just not sure what i am doing wrong and why it is not saving or updating the ui text! i will attach the coin manager script and also the game manager script! in the game manager script it is the start game routine and end game routine functions where i am having trouble! i appreciate your help with this thank you.
public class CoinManager : Singleton <CoinManager> {
public Text coinText;
public int oldCoinCoint = 0;
// returns the number of coins stored in PlayerPrefs
public int GetCoinCount()
{
if (PlayerPrefs.HasKey("TotalCoins"))
{
return PlayerPrefs.GetInt("TotalCoins");
}
// if we don't have the key set, so return 0
return 0;
}
// sets a number of coins into PlayerPrefs if the coin count is greater
public void SetCoinCount(int coinAmount)
{
if (PlayerPrefs.HasKey("TotalCoins") && (coinAmount > oldCoinCoint))
{
PlayerPrefs.SetInt("TotalCoins", coinAmount);
}
}
// display the coin count as a TextUI
public void ShowCoinCount()
{
int coinCount = GetCoinCount();
if (coinText != null)
{
coinText.text = coinCount.ToString();
}
}
//new method for oldcoin count
public void AddCoins(int coins)
{
oldCoinCoint = oldCoinCoint + coins;
}
}
here is the game manager script...
[RequireComponent(typeof(LevelGoal))]
public class GameManager : Singleton<GameManager>
{
//for level unlock
[SerializeField]
string m_nextLevel;
//new for level unlock system
public string levelTag;
//testing for coins
//private ScoreManager scoreManager;
//for coins
//private CoinManager coinManager;
// reference to the Board
Board m_board;
// is the player read to play?
bool m_isReadyToBegin = false;
// is the game over?
bool m_isGameOver = false;
public bool IsGameOver
{
get {
return m_isGameOver;
}
set
{
m_isGameOver = value;
}
}
// do we have a winner?
bool m_isWinner = false;
// are we ready to load/reload a new level?
bool m_isReadyToReload = false;
LevelGoal m_levelGoal;
//LevelGoalTimed m_levelGoalTimed;
LevelGoalCollected m_levelGoalCollected;
public LevelGoal LevelGoal {get{return m_levelGoal; }}
public override void Awake()
{
base.Awake();
m_levelGoal = GetComponent<LevelGoal>();
//m_levelGoalTimed = GetComponent<LevelGoalTimed> ();
m_levelGoalCollected = GetComponent<LevelGoalCollected> ();
// cache a reference to the Board
m_board = GameObject.FindObjectOfType<Board>().GetComponent<Board>();
//testing for coins
//scoreManager = GetComponent<ScoreManager> ();
}
void Start()
{
if (UiManager.Instance != null)
{
if (UiManager.Instance.scoreMeter != null)
{
UiManager.Instance.scoreMeter.SetupStars(m_levelGoal);
}
// use the Scene name as the Level name
if (UiManager.Instance.levelNameText != null)
{
// get a reference to the current Scene
Scene scene = SceneManager.GetActiveScene();
UiManager.Instance.levelNameText.text = scene.name;
}
if (m_levelGoalCollected != null)
{
UiManager.Instance.EnableCollectionGoalLayout (true);
UiManager.Instance.SetupCollectionGoalLayout (m_levelGoalCollected.collectionGoals);
}
else
{
UiManager.Instance.EnableCollectionGoalLayout (false);
}
bool useTimer = (m_levelGoal.levelCounter == LevelCounter.Timer);
UiManager.Instance.EnableTimer (useTimer);
UiManager.Instance.EnableMovesCounter (!useTimer);
}
// update the moves left UI
m_levelGoal.movesLeft++;
UpdateMoves();
// start the main game loop
StartCoroutine("ExecuteGameLoop");
}
// update the Text component that shows our moves left
public void UpdateMoves()
{
if (m_levelGoal.levelCounter == LevelCounter.Moves)
{
m_levelGoal.movesLeft--;
if (UiManager.Instance != null && UiManager.Instance.movesLeftText != null)
{
UiManager.Instance.movesLeftText.text = m_levelGoal.movesLeft.ToString ();
}
}
}
// this is the main coroutine for the Game, that determines are basic beginning/middle/end
// each stage of the game must complete before we advance to the next stage
// add as many stages here as necessary
IEnumerator ExecuteGameLoop()
{
yield return StartCoroutine("StartGameRoutine");
yield return StartCoroutine("PlayGameRoutine");
// wait for board to refill
yield return StartCoroutine("WaitForBoardRoutine", 0.5f);
yield return StartCoroutine("EndGameRoutine");
}
// switches ready to begin status to true
public void BeginGame()
{
m_isReadyToBegin = true;
}
// coroutine for the level introduction
IEnumerator StartGameRoutine()
{
//for coins
if (CoinManager.Instance != null)
{
CoinManager.Instance.ShowCoinCount();
}
if (UiManager.Instance != null)
{
// show the message window with the level goal
if (UiManager.Instance.messageWindow != null)
{
UiManager.Instance.messageWindow.GetComponent<RectXformMover>().MoveOn();
int maxGoal = m_levelGoal.scoreGoals.Length - 1;
UiManager.Instance.messageWindow.ShowScoreMessage(m_levelGoal.scoreGoals[maxGoal]);
if (m_levelGoal.levelCounter == LevelCounter.Timer)
{
UiManager.Instance.messageWindow.ShowTimedGoal (m_levelGoal.timeLeft);
}
else
{
UiManager.Instance.messageWindow.ShowMovesGoal (m_levelGoal.movesLeft);
}
if (m_levelGoalCollected != null)
{
UiManager.Instance.messageWindow.ShowCollectionGoal (true);
GameObject goalLayout = UiManager.Instance.messageWindow.collectionGoalLayout;
if (goalLayout != null)
{
UiManager.Instance.SetupCollectionGoalLayout (m_levelGoalCollected.collectionGoals, goalLayout, 80);
}
}
}
}
// wait until the player is ready
while (!m_isReadyToBegin)
{
yield return null;
}
// fade off the ScreenFader
if (UiManager.Instance != null && UiManager.Instance.screenFader != null)
{
UiManager.Instance.screenFader.FadeOff();
}
// wait half a second
yield return new WaitForSeconds(0.5f);
// setup the Board
if (m_board != null)
{
m_board.SetupBoard();
}
}
// coroutine for game play
IEnumerator PlayGameRoutine()
{
if (m_levelGoal.levelCounter == LevelCounter.Timer)
{
m_levelGoal.StartCountdown ();
}
// while the end game condition is not true, we keep playing
// just keep waiting one frame and checking for game conditions
while (!m_isGameOver)
{
m_isGameOver = m_levelGoal.IsGameOver();
m_isWinner = m_levelGoal.IsWinner();
// wait one frame
yield return null;
}
}
IEnumerator WaitForBoardRoutine(float delay = 0f)
{
if (m_levelGoal.levelCounter == LevelCounter.Timer && UiManager.Instance != null &&
UiManager.Instance.timer != null)
{
UiManager.Instance.timer.FadeOff ();
UiManager.Instance.timer.paused = true;
}
if (m_board != null)
{
// this accounts for the swapTime delay in the Board's SwitchTilesRoutine BEFORE ClearAndRefillRoutine is invoked
yield return new WaitForSeconds(m_board.swapTime);
// wait while the Board is refilling
while (m_board.isRefilling)
{
yield return null;
}
}
// extra delay before we go to the EndGameRoutine
yield return new WaitForSeconds(delay);
}
// coroutine for the end of the level
IEnumerator EndGameRoutine()
{
// set ready to reload to false to give the player time to read the screen
m_isReadyToReload = false;
//for coin test
//PlayerPrefs.SetInt ("coinCount", scoreManager.CurrentScore);
// if player beat the level goals, show the win screen and play the win sound
if (m_isWinner)
{
ShowWinScreen ();
PlayerPrefs.SetInt(levelTag, 1);
Unlocklevel(m_nextLevel);
//PlayerPrefs.SetInt ("coinCount", ScoreManager.Instance.coinValue);
//for coins
if (CoinManager.Instance != null)
{
CoinManager.Instance.AddCoins(50);
CoinManager.Instance.SetCoinCount(CoinManager.Instance.oldCoinCoint);
CoinManager.Instance.ShowCoinCount();
}
}
// otherwise, show the lose screen and play the lose sound
else
{
ShowLoseScreen ();
}
// wait one second
yield return new WaitForSeconds(1f);
// fade the screen
if (UiManager.Instance != null && UiManager.Instance.screenFader != null)
{
UiManager.Instance.screenFader.FadeOn();
}
// wait until read to reload
while (!m_isReadyToReload)
{
yield return null;
}
// reload the scene (you would customize this to go back to the menu or go to the next level
// but we just reload the same scene in this demo
SceneManager.LoadScene("Map"); //SceneManager.GetActiveScene().name);
}
//temp copy from levellocks script to test
public void Unlocklevel(string level)
{
PlayerPrefs.SetInt(level, 1);
PlayerPrefs.Save();
}
void ShowWinScreen ()
{
if (UiManager.Instance != null && UiManager.Instance.messageWindow != null)
{
UiManager.Instance.messageWindow.GetComponent<RectXformMover> ().MoveOn ();
UiManager.Instance.messageWindow.ShowWinMessage ();
UiManager.Instance.messageWindow.ShowCollectionGoal (false);
if (ScoreManager.Instance != null)
{
string scoreStr = "you scored\n" + ScoreManager.Instance.CurrentScore.ToString () + " points!";
UiManager.Instance.messageWindow.ShowGoalCaption (scoreStr, 0, 70);
}
if (UiManager.Instance.messageWindow.goalCompleteIcon != null)
{
UiManager.Instance.messageWindow.ShowGoalImage (UiManager.Instance.messageWindow.goalCompleteIcon);
}
}
if (SoundManager.Instance != null)
{
SoundManager.Instance.PlayWinSound ();
}
}
void ShowLoseScreen ()
{
if (UiManager.Instance != null && UiManager.Instance.messageWindow != null)
{
UiManager.Instance.messageWindow.GetComponent<RectXformMover> ().MoveOn ();
UiManager.Instance.messageWindow.ShowLoseMessage ();
UiManager.Instance.messageWindow.ShowCollectionGoal (false);
string caption = "";
if (m_levelGoal.levelCounter == LevelCounter.Timer)
{
caption = "Out of time!";
}
else
{
caption = "Out of moves!";
}
UiManager.Instance.messageWindow.ShowGoalCaption (caption, 0, 70);
if (UiManager.Instance.messageWindow.goalFailedIcon != null)
{
UiManager.Instance.messageWindow.ShowGoalImage (UiManager.Instance.messageWindow.goalFailedIcon);
}
}
if (SoundManager.Instance != null)
{
SoundManager.Instance.PlayLoseSound ();
}
}
// use this to acknowledge that the player is ready to reload
public void ReloadScene()
{
m_isReadyToReload = true;
}
// score points and play a sound
public void ScorePoints(GamePiece piece, int multiplier = 1, int bonus = 0)
{
if (piece != null)
{
if (ScoreManager.Instance != null)
{
// score points
ScoreManager.Instance.AddScore(piece.scoreValue * multiplier + bonus);
// update the scoreStars in the Level Goal component
m_levelGoal.UpdateScoreStars(ScoreManager.Instance.CurrentScore);
if (UiManager.Instance != null && UiManager.Instance.scoreMeter != null)
{
UiManager.Instance.scoreMeter.UpdateScoreMeter(ScoreManager.Instance.CurrentScore,
m_levelGoal.scoreStars);
}
}
// play scoring sound clip
if (SoundManager.Instance != null && piece.clearSound !=null)
{
SoundManager.Instance.PlayClipAtPoint(piece.clearSound, Vector3.zero, SoundManager.Instance.fxVolume);
}
}
}
public void AddTime(int timeValue)
{
if (m_levelGoal.levelCounter == LevelCounter.Timer)
{
m_levelGoal.AddTime (timeValue);
}
}
public void UpdateCollectionGoals(GamePiece pieceToCheck)
{
if (m_levelGoalCollected != null)
{
m_levelGoalCollected.UpdateGoals (pieceToCheck);
}
}
}
Answer by Lysander · Jan 03, 2018 at 09:34 AM
My guess is that it's because you're checking if the key exists before setting it. That means if it's never been set before, it'll never be set- there's no safety concern here, so just set it if/when the coin count is larger.