- Home /
Is there anyway to shorten this code?
private void Start() { experienceStatic = PlayerPrefs.GetInt("experience");
if (playerLevel == 1)
{
PlayerHealth.maxHealth += 1;
}
if (playerLevel == 2)
{
PlayerHealth.maxHealth += 2;
}
if (playerLevel == 3)
{
PlayerHealth.maxHealth += 3;
}
if (playerLevel == 4)
{
PlayerHealth.maxHealth += 4;
}
if (playerLevel == 5)
{
PlayerHealth.maxHealth += 5;
}
if (playerLevel == 6)
{
PlayerHealth.maxHealth += 6;
}
if (playerLevel == 7)
{
PlayerHealth.maxHealth += 7;
}
if (playerLevel == 8)
{
PlayerHealth.maxHealth += 8;
}
if (playerLevel == 9)
{
PlayerHealth.maxHealth += 9;
}
if (playerLevel == 10)
{
PlayerHealth.maxHealth += 10;
}
}
Answer by Maypher · Jan 14, 2021 at 04:23 PM
If you're adding the same amount of health as the level your character's at (if at level 6, add 6 HP) You can simplify your code to this:
PlayerHealth.maxHealth += playerLevel
This way no matter which level you're on it will add that amount of health
sorry I didnt include that part.. oops
if (experience >= 10) { playerLevel = 1;
}
if (experience >= 50)
{
playerLevel = 2;
}
if (experience >= 100)
{
playerLevel = 3;
}
if (experience >= 200)
{
playerLevel = 4;
}
if (experience >= 300)
{
playerLevel = 5;
}
if (experience >= 500)
{
playerLevel = 6;
}
if (experience >= 1000)
{
playerLevel = 7;
}
if (experience >= 1500)
{
playerLevel = 8;
}
if (experience >= 2000)
{
playerLevel = 9;
}
if (experience >= 3000)
{
playerLevel = 10;
}
any way to shorten this as well?
I created 2 functions that will simplify that code and the original question's. So you'll only need one script to handle both values.
int currentXP = 0;
int xpToNextLevel = 100; //This can be anything, it's the required XP to advance to the next level.
int currentPlayerLevel = 1;
int $$anonymous$$axHealth = 10; //Base health at level 1
void addExperience(int amount)
{
currentXP += amount;
if (currentXP >= xpToNextLevel)
{
levelUp();
}
}
void levelUp()
{
xpToNextLevel = 200; //Set the required XP to advance again
currentXP = 0; //Reset XP
currentPlayerLevel += 1; //Add 1 level to the player
$$anonymous$$axHealth += currentPlayerLevel;
}
Now you just need to call the "addExperience" function whenever you want to give your character XP. Note this doesn't handle multi-level upgrade, so if you go up 3 levels at once you'll have to figure out how to handle that.
Your answer
Follow this Question
Related Questions
How do I change scenes from triggers in UNity 1 Answer
Unity game level design patterns 0 Answers
How to add multiple levels? 3 Answers
players create level 0 Answers
Multiple Scenes for Multiple Levels, or One Scene with all Levels? 1 Answer