Inputting another scripts variable as a float
Hi! So I'm trying to make my health bar script more efficient. As of right now it does a GetComponent check every frame, which seems unreasonable. So what I'm wanting to know is can I replace a GetComponent by directly accesesing the scripts traits through a public variable? Right now I have
public GameObject owner;
void Update () {
{
CurrentHealth = (float)owner.GetComponent<PlayerHealth> ().Health;
HealthMax = (float)owner.GetComponent<PlayerHealth> ().MaxHealth;
}
This script works, but could I replace it with
public Health PlayersHealth;
public MaxHealth PlayerMax;
void Update () {
CurrentHealth = (float)PlayersHealth;
HealthMax = (float)PlayerMax;
}
If it's not doable it will be fine, but if I can do this small amount of pollish it would be very relieving.
Answer by donutLaserDev · Mar 21, 2018 at 01:03 PM
You could do it this way (assuming that you can just assign PlayerHealth component to this script in the Inspector):
public PlayerHealth playerHealth;
void Update () {
CurrentHealth = (float)playerHealth.Health;
HealthMax = (float)playerHealth.MaxHealth;
}
Alternatively, you could get the playerHealth in Awake:
void Awake () {
playerHealth = owner.GetComponent<PlayerHealth> ();
}
This way you'll only have to call GetComponent once.
I tried the first method and it works great, thanks for the help!