- Home /
Decrease a value every second?
Hello, I'm trying to make a little function in C# ... I'd like to decrease a value by 1 every second, here my Code:
private int hunger= 100;
void decreaseHunger(){
while (0 < hunger) {
Time.deltaTime -= 1; // IM SURE THIS ONE IS ULTRA WRONG
hunger -= 1;
}
}
void Update(){
Debug.log(hunger);
}
Thanks guys!
Answer by tanoshimi · Jul 21, 2017 at 05:01 PM
You're right - it is ultra wrong! Try this:
private int hunger= 100;
void Start(){
InvokeRepeating("decreaseHunger", 1.0f, 1.0f);
}
void decreaseHunger(){
if(hunger > 0) {
hunger -= 1;
}
}
void Update(){
Debug.log(hunger);
}
Answer by megabrobro · Jul 21, 2017 at 05:31 PM
the Time.delta returns a value of how long it took to do the last update cycle. AFAIK the normal method is to have a variable called timeCountInSeconds or something, then in the update loop just do timeCountInSeconds += Time.delta;
That will give you a count showing the actual seconds
Hope this helps.
Answer by ArtC0de · Jul 21, 2017 at 05:21 PM
Worked very smoothly ! Thanks a lot and sorry for my newbie errors, I'm still learning :)
im new too. but i found it easier to understand my version which ive typed below. Please forgive me if i misunderstood what u meant
Your answer
Follow this Question
Related Questions
for loop problem,problem with for loop 1 Answer
Adding a value to a variable every second 4 Answers
Do-While loop 2 Answers