How can change the text in UI text component each 5 seconds after start timer
public Text Energy;
public float EnergyMax = 100.0f;
void update(){
// timer
timer += Time.deltaTime;
if( timer == 5 ) {
Energy.text = "Energy: " + ( EnergyMax - 5.0f);
}
}
EnergyMax is set to 100. When I start the play the game the timer start. Each 5 seconds I want edit the Energy.text 5 sec. 95, 10 sec. 90 and etc .... How write the condition correctly? The function InvokeRepeating not working well for me ....
Answer by Saryk360 · Aug 07, 2017 at 02:11 PM
First off you'll want to check if (timer >= 5)
. Then, you need to reset the timer after these 5 seconds, so set timer = 0;
in your condition. And lastly, your variable name EnergyMax
is misleading because you use it as a "Current Energy" variable.
As to InvokeRepeating, here's how you'd use it :
Start() {
[...]
currentEnergy = energyMax;
//call DepleteEnergy() after a delay of 0.01 seconds, and then every 5 seconds
InvokeRepeating("DepleteEnergy", 0.01f, 5f);
}
void DepleteEnergy() {
//substract energyDepletionValue (in your case, 5.0f) from currentEnergy
currentEnergy -= energyDepletionValue;
energy.text = "Energy: " + (currentEnergy);
}
:)
Note that if you set InvokeRepeating()
to start after a delay of 0, it behaves weirdly. It's better to use some very small number.
Your answer
Follow this Question
Related Questions
How to record lap time for player and AIs? 0 Answers
Milliseconds Timer Question 1 Answer
how can i take time value from timer (Asked again clearly) 2 Answers
How to make an App that only works for a week? 1 Answer
How is it possible to verify values and is they are correct activate objects ? 0 Answers