Hello. I feel this is a bit of a beginner question, but I couldn’t wrap my head around it. I’ve tried using getter and setter for this, but I didn’t manage to get it to work. I’m still new to a lot of coding aspects, so please bear with me on this.
What I am trying to do, is to give a character a set amount of stat points when that character reaches a new level. Then, naturally, what I want to happen is that the character only gets the stat points once, not every frame it is true that the character is that level.
My current code:
public class CharacterLevelScript : MonoBehaviour {
public int currentLevel;
public int currentExp;
public int statPoints;
public GameObject[] enemies;
void Start () {
currentLevel = 1;
}
void Update () {
List<GameObject> enemyList = new List<GameObject> ();
enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in enemies) {
enemyList.Add(enemy);
}
foreach(GameObject enemy in enemyList) {
EnemyHealth eh = (EnemyHealth)enemy.GetComponent("EnemyHealth");
if(enemy.gameObject) {
if(eh.curhp <= 0f) {
currentExp += eh.xpGiven;
}
}
}
if(currentExp >= 0 && currentExp <=100) {
currentLevel = 1;
}
else if(currentExp >= 101 && currentExp <= 500) {
currentLevel = 2;
}
else if(currentExp >= 501 && currentExp <= 1000) {
currentLevel = 3;
}
What I’ve tried working with, but failed to get it to work:
public int currentLevel;
public int CurrentLevel {
get {
return currentLevel;
}
set {
statPoints += 5;
currentLevel = value;
}
}
Doesn’t get much more simple than this, you don’t have to define what happens for each level. If you want to double the needed exp to level up, just do so each time the code runs.
public int currentLevel;
public int currentExp;
public int statPoints;
public int statPointsToAdd;
public int expToLevelUp;
void Start () {
currentLevel = 1;
}
void Update(){
if(currentExp>=expToLevelUp){
currentExp=0;
statPoints+=statPointsToAdd;
currentLevel+=1;
}
}