- Home /
The question is answered, right answer was accepted
How do i make a script that re-fills lives after 10min?
EDIT i got the life going down mechanics, i just need the time script. Everytime deaths go to 5 in a level i want to lower the PlayerPrefs for the Big Lives(ones in the menu, that decide wether you can play or not) by one. I dont know how to just decrease it instead of setting the PlayerPrefs to a specific number. Also if Big Lives <= 5 i want a timer to start that of reaches 10 min it would replenish one Big Life. But i cant really find anything. Can anybody help?
Answer by Box_Frog · Feb 15, 2021 at 06:26 PM
If you just want to decrease the number by one you could do: bigLives--;
or if you want to decrease by a certain number then you do this: bigLives-= 2;
which subtracts two from the value.
For the timer I usually make something like this with the startLifeTimer being the amount between each live. Then subracting one second from lifeTimer until it equals 0, where we add a life and reset the timer.
float startLifeTimer;
float lifeTimer;
void Start
{
lifeTimer = startLifeTimer;
}
if(bigLives <= 5)
if(lifeTimer < 0)
{
bigLives++;
PlayerPrefs.SetFloat("BigLives", bigLives);
lifeTimer = startLifeTimer;
}
else
{
lifeTimer -= Time.deltaTime;
}
Is there a way i could store bigLives in PlayerPrefs? I said i got it but it didnt work as i wanted. Also, on the last row was there supposed to be lifeTimer -=Time.deltaTime?
I edited my answer. This is how I would store it in PlayerPrefs and yea the last line was just a typo meant to put lifeTimer.
I will try it tommorow as its linda late here. I guess startLifeTimer should be the time I want it to take for a life to replenish?
Answer by logicandchaos · Feb 15, 2021 at 06:39 PM
use coroutines, so something like this:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
void Start()
{
StartCoroutine(ResetLives);
}
private IEnumerator ResetLives()
{
while(true)
{
yield return new WaitForSeconds(10f);
player.lives=10;
}
}
}
More info on coroutines:
https://docs.unity3d.com/ScriptReference/Coroutine.html
https://stackoverflow.com/questions/53139259/making-a-timer-in-unity
Is this C#? It looks kinda different from what ive seen until now. I will try it tommorow as its kinda late here, thx
Yes it is C#, this is a common unity functionality to execute iterative code outside of the main Update() loop