- Home /
Accessing a Variable in another script for (SLIDER)
Hey guys, I've been trying to figure this out all day, there's not much info on the 4.6 UI like there is for the older GUI.
Well, here's what I am trying to do.
I have a health variable in another script, I have the SLIDER for the health bar on my player.
(pretty much shows the Enemies health bar on the Players screen)
Well, I've tried so many different ways to get this to work. I've tried GetComponent, I've tried GameObject.Find, every time I try an get an error of some sort.
I Commented out all the code just so you can see all the different ways I tried this. I just don't understand this.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GreenSodaRefineryCheckHealth : MonoBehaviour {
public Slider HealthSlider; // THE HEALTH SLIDER ON PLAYER
public GameObject GreenSodaRef; // THE REFERENCED GAMEOBJECT WITH VARIABLE FOR HEALTH
public EmissionsStack GreenSodaBuilding; // THIS NEITHER WORKS AS WELL. IT WON'T LET ME DO GAMEOBJECT.FIND TO PUT IT IN HERE.
// Use this for initialization
void Start () {
// THIS IS THE GAMEOBJECT.FIND CODE.
//GreenSodaRef = GameObject.Find ("GreenSodaRefinery").GetComponent<EmissionsStack>();
//GreenSodaRef = GameObject.Find ("GreenSodaRefinery");
//GreenSodaBuilding = gameObject.Find ("GreenSodaRefinery").GetComponent<EmissionsStack>();
//GreenSodaBuilding.curHealth; // IT CANT FIND THE "curHealth" VARIABLE - (IT STAYS RED);
}
// Update is called once per frame
void Update () {
// THIS IS THE ONLY WAY I SLIGHTLY GET RESULTS (IT JUST CAN'T FIND THE GAMEOBJECT
// BUT IT LETS ME ACCESS THE VARLIABLE "curHealth" BUT IS POINTLESS AS IT
// CAN'T FIND THE GAMEOBJECT IT IS ON.
HealthSlider.value = GreenSodaBuilding.curHealth;
//EmissionsStack other = GameObject.Find ("GreenSodaRefinery");
//EmissionsStack other = GetComponent<EmissionsStack> ();
//HealthSlider.value = other.curHealth;
//HealthSlider.value = GreenSodaRef.curHealth;
}
}
The HealthSlider.Value = GreenSodaBuilding.curHealth; is the main thing I am trying to get to work. But I keep getting errors like GameObject can't be type Value and stuff like like.
Answer by N1warhead · Jan 08, 2015 at 02:52 AM
Well I figured it out finally, it was a bit different way than I normally do things, but I got it.
I'm not sure how Optimized this is, but it works lol.
Here is the code in the UPDATE function
void Update () {
GameObject other = GameObject.Find ("GreenSodaRefinery");
HealthSlider.value = other.gameObject.GetComponent<EmissionsStack> ().curHealth;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
4.6 UI Canvas is smaller than normal 1 Answer
Canvas & Player spawning 1 Answer
Unity 4.5 - Can't find UI in the “Create” list 2 Answers
Floating Enemy Health Bars? 1 Answer