I have implemented a skill system into my game where each skill levels up individually (so basically Skyrim) but I am having trouble making a progress bar for the skill. I want the bar to fill up by the percent that the skill has increased. Here is the code I currently have:
public void UpdateProgressBar()
{
skillBlock.GetComponent<SkillSlot>().UpdateProgressBar(currentXP/expToNextLevel * 100);
}
and on the UI element that controls the bar itself I have:
public void UpdateProgressBar(int progress)
{
expBar.sizeDelta = new Vector2(progress, expBar.sizeDelta.y);
}
Nothing complicated but the bar never shows up, it just remains blank. I tried other ways before, like using âexpToNextLevel - currentXPâ and that made the bar work totally fine (with the exception that the bar went down instead of up which is what I want) so I know its not a problem with the bar itself. Does anyone know how to make the bar appear properly with the percentage of the skill?
Thanks all!
also, side question, I am using the Unity tutorials for the health bar system to create these bars. It works fine but instead of it going from left to right like I want, the bar stretches from the middle. Is there an easy way to change this? Iâll do some research on this one so if its not an easy answer donât worry about it.
Ah that makes more sense. It would be more flexible. How do I convert an int to a float? Can I just use âcurrentXP.fâ and do that for each variable?
Note that for things like XP, you want to keep storing the value as an int, and only cast to float when youâre displaying it. This is due to float being inherently slightly inaccurate - after all, thereâs an infinite number of possible values between 0 and 1, and your computer canât differentiate between all of those.
I may end up using a code just like this in the function as a temporary variable. I definitely donât want to keep track of exp with floats permanently, I just need it for display purposes. Thanks for the advise!
This looks like a pretty solid way to go. My only difficulty with it is the two functions I listed originally are on two separate scripts. So should I get the float in the first script and pass that to the script that updates the bar, or should I pass the ints to the bar script and do the math there? The way its written above looks like it will work if everything is in the same script.
I finally got to try the code out and your suggestion works perfectly! I added thr (float) to the first code and just changed the int to float in the script that accepts the data. Workin just fine!
I have 1 tiny problem where when I level up a skill, the bar updates as it should but since the math is based off currentXP/expToNextLevel, the bar starts off half way full. I guess really I want the bar to be the percent of the previous expToNextLevel/expToNextLevel. Is there a way to do that without making a new variable, or should I just make a new variable?