- Home /
Unity UI : Attached Gameobjetcs resets when starting the game
So i am making a idle game in Unity with UI elements.
This game has a motivation bar wich is made of a slider.
Above this slider is a text wich shows the %, the value is taken from the slider value.
To the slider´s script, which updates the value, i attached the text and the slider.
It looks like this before i click Play : https://puu.sh/wYBpz/1713661617.png
But when i click Play, it resets : https://puu.sh/wYBrl/6a4fed033c.png
And after i stopped playing in Unity, the text is attached again like in the first picture.
Someone knows a fix?
Btw. this is my script attached to the slider :
public Slider motivationSlider;
public Text motivationValue;
// Use this for initialization
void Start () {
motivationSlider = gameObject.GetComponent<Slider>();
motivationValue = gameObject.GetComponent<Text>();
}
// Update is called once per frame
void Update () {
ChangePercentage();
}
public void ChangePercentage()
{
float SliderValue = motivationSlider.value;
motivationValue.text = SliderValue.ToString() + " %";
}
Answer by Elthen · Aug 03, 2017 at 07:39 AM
You don't need to get the component inside Start() since it's already public and has a reference to it from the inspector.
My bet is that there is no Text attached to the current object (where you have the script) and thus when it tries to get a component it can't find anything.
Just remove motivationValue = gameObject.GetComponent();