Hello people of Unity Answers! I basically want to get my Level and XP system to work properly. I mean… It works very well but I cant find the one logic error. As you can see in the script, I have coded it very simple (cuz my programming skill is not good lol) and it has only one Error. This is how the one part should be: If you level up, your current XP gets subtracted by the XP-requirement (So if the XP is larger then the required XP, the rest stays). The problem is, that if the player levels up, the XP changes to a negative number (Even if the XP is larger than the required XP). It somehow subtracts the XP twice or something… Please Help me and please tell me, how to find bugs easier. I always use Debug.Log(), are there any better techniques or something?
private WallController wallController;
private PlayerStats playerStats;
public float AllCollectedXp;
public bool CanLvlUp;
public static LevelAndXpManager instance;
void Start()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this);
}
else if (instance != null)
{
Destroy(gameObject);
}
playerStats = FindObjectOfType<PlayerStats>().GetComponent<PlayerStats>();
}
void Update()
{
if (CanLvlUp)
{
LvlUp();
CheckIfCanLvlUp();
}
}
public void IncreaseCollectedXp(float Xp)
{
AllCollectedXp += Xp;
}
public void CheckChangeSetLvlAndXp()
{
ChangePlayerXp();
CheckIfCanLvlUp();
if (CanLvlUp)
{
LvlUp();
}
}
public void ChangePlayerXp()
{
playerStats.playerXp += AllCollectedXp;
AllCollectedXp = 0;
PlayerPrefs.SetFloat("playerXp", playerStats.playerXp);
}
public void CheckIfCanLvlUp()
{
if (playerStats.playerXp >= playerStats.XpToLvlUp)
{
CanLvlUp = true;
}
else CanLvlUp = false;
}
public void LvlUp()
{
playerStats.playerXp -= playerStats.XpToLvlUp;
Debug.Log(playerStats.playerXp);
playerStats.playerLvl++;
playerStats.XpToLvlUp += 50;
PlayerPrefs.SetInt("playerLvl", playerStats.playerLvl);
PlayerPrefs.SetFloat("playerXp", playerStats.playerXp);
PlayerPrefs.SetFloat("XpToLvlUp", playerStats.XpToLvlUp);
}
}