- Home /
Player Prefs adding XP randomly
Dear coders I have a player who can gain XP in a number of ways in game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerXP : MonoBehaviour {
public int currentLevel;
public int currentXP;
public int maxXP;
public int minXP;
public int xpToLevelUp;
public int [] toLevelUp;
void Start () {
currentXP = PlayerPrefs.GetInt ("playerXP");
minXP = 0;
}
// Update is called once per frame
void Update (){
PlayerPrefs.SetInt ("playerXP", currentXP);
PlayerPrefs.SetInt ("maxXP", maxXP = 900);
}
I can save this XP figure via PlayerPrefs when I exit the game screen into the Start Game Scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class EnterItemCollectLevel : MonoBehaviour {
public int currentXP;
public int newXP;
public int maxXP;
void Start (){
currentXP = PlayerPrefs.GetInt ("playerXP");
maxXP = PlayerPrefs.GetInt ("maxXP");
}
void Update ()
{
if (Input.GetKey (KeyCode.I)) {
SceneManager.LoadScene (2);
}
However, when I go back into the Game Scene (scene 2) from the Start Game scene the XP seems to randomly add 100 to the player XP.
I've used this same method for saving health stats without any issue but for some reason it does not seem to be working for XP.
Could anybody help?
Thanks in advance!
Answer by Nobozarb · Jan 13, 2018 at 10:33 PM
If it is adding exactly 100 XP every time but doing nothing for the health it seems that this would likely be code you wrote in order to test something in your game but then forgot to remove that code.
Your game also seems to be the type of game where there are monsters or some type of thing that you can kill. It is possible one of those is giving the reward for killing it before it actually dies?
Answer by ohkayem · Jan 15, 2018 at 09:08 PM
Thankyou very much for this. The problem is that when I go from Scene 1 to Scene 2, the XP already collected seems to accumulate and increase the level.
The levelling up is in an array :
void Update (){
PlayerPrefs.SetInt ("playerXP", currentXP);
PlayerPrefs.SetInt ("maxXP", maxXP = 900);
xpToLevelUp = toLevelUp[currentLevel];
if (currentXP > maxXP) {
currentXP = maxXP;
}
if (currentXP >= maxXP) {
currentXP = maxXP;
}
if (currentXP > xpToLevelUp) {
LevellingUp ();
}
}
public void LevellingUp(){
if (currentXP > toLevelUp [currentLevel]) { (do stuff)
I've tried saving the player level via playerprefs but this just does not seem to be working at all - the level is just stuck at the inital one that the player starts at. Does this have anything to do with the levels being in the form of an array?
Thanks!
Your answer
Follow this Question
Related Questions
Need help with PlayerPrefs 2 Answers
Grabbing PlayerPrefs variables from another game. 0 Answers
[SOLVED] A Playerpref in one place is blocking all my other Playerprefs 1 Answer
Help with RPG 2 Answers