- Home /
Trying to get 2 floats synced up.
Hey guys, using NGUI to make a Health bar, problem is that the progress bars float has a value of 0 to 1, but my Health is 0 - 100, I was wondering how I would be able to hook it up so that the health and the NGUI bar is the same value and will increase and decrease respectfully.
Here's what I have so far, I just don't know how to hook it up.
using UnityEngine;
using System.Collections;
public class HealthBarLink : MonoBehaviour {
private UISlider _slider;
public GameObject Player;
void Update()
{
_slider = GetComponent<UISlider>();
Health = Player.GetComponent<Health>();
Health.curHealth == _slider.rawValue;
}
}
The rawValue part is where I'm having trouble.
I knew it'd have to be something like, not sure how to properly implement it in code though. :/
Answer by hijinxbassist · May 31, 2012 at 08:12 AM
void Update()
{
_slider = GetComponent<UISlider>();
Health = Player.GetComponent<Health>();
_slider.rawValue = Health.curHealth/100;
}
I think this is what you want. However you dont need to do it in update, just change the rawValue to curHealth/100 whenever the health decreases. This way you do not need to check/change the value every frame. Heres an example of how to update the rawValue when your player takes damage.
//Health.cs
void Damage(float damage)
{
curHealth-=damage;
_slider = GetComponent<UISlider>();
_slider.rawValue=curHealth/100;
}
Answer by jorgenpt · May 31, 2012 at 08:54 AM
You probably want to do the following:
// Cache these values on startup
void OnEnable ()
{
_slider = GetComponent<UISlider>();
Health = Player.GetComponent<Health>();
}
// Make UISlider match health
void Update()
{
_slider.sliderValue = Health.curHealth/Health.maxHealth;
}
Assuming you have a Health.maxHealth. :-)
I hope this helps!
Yeah, like hijinxbassist says - you should probably only update sliderValue in your "Damage" code, as it'll be faster. (and it'll be the only place the value of the slider changes)
Your answer
Follow this Question
Related Questions
Slider calculations go wrong 1 Answer
Calling a c# script from js [for NGUI] 1 Answer
Public Health Var C# 1 Answer
Float not resetting when I instantiate new player prefab 1 Answer
Health script 0 Answers