- Home /
typecasting GameObject & UI slider
I have searched everywhere for the answer to this and can't find it (in c#), but i know this is super simple:
I have a UI slider that i am using as a health bar, i took alot of the code from the Unity Survival Shooter tutorial. My problem is this: In the tutorial the scene starts with a player already in the hierarchy, so all they had to do to apply the slider to their player.health was drag and drop in the editor.
In my game the player is instantiated by a GameManager after initialization so i can't just drag and drop the slider using the editor.
In my script i have a declaration of: public Slider healthSlider; Trying to get to that Slider through my script is proving to be way harder than i know it should be.
I tried using: healthSlider = GameObject.FindGameObjectWithTag ("healthslider"); this won't work because i can't convert GameObject to Slider. So I tried: healthSlider = (Slider) GameObject.FindGameObjectWithTag ("healthslider"); (trying to find the slider as a GameObject and typecast it to a slider, same problem basically.
Now I just can't think of what else to try. All I'm trying to do is get a reference to that Slider. Currently it is a child of a UI>Canvas, does that matter?
Thank you in advance for your help, i know this is an easy one. :)
Answer by Ruffer07 · Dec 23, 2017 at 07:12 PM
I'm not sure if you are still struggling with this, but I just hit this problem with my custom editor for an audio/music player script I'm currently in the process of making.
Try casting to (UnityEngine.UI.Slider)
instead of (Slider)
.
So
healthSlider = (UnityEngine.UI.Slider) GameObject.FindGameObjectWithTag ("healthslider");