while loop gives me float “mana” at the speed of light do you know how to slow it down?
simplified code
public static float mana = 1;
void Update()
{
while (mana < 100)
{
mana++;
}
}
while loop gives me float “mana” at the speed of light do you know how to slow it down?
simplified code
public static float mana = 1;
void Update()
{
while (mana < 100)
{
mana++;
}
}
Hi @BadLucky,
Because Update is executed at each frame, you can use a Coroutine to make it slower. Here is the code:
public static float mana = 1;
[SerializeField]
private float timer = 1f;
private void Start()
{
StartCoroutine(AddMana()); // Start your coroutine loop
}
private IEnumerator AddMana()
{
while (mana < 100)
{
mana++;
yield return new WaitForSeconds(timer); // Wait for x seconds before playing this function again.
}
// Do stuff after mana full ...
}
As indicated by AntoineHeseque, Update
is ran once each frame.
You can use a coroutine to wait for a given time between each tick, or you can keep the Update for a continuous increase and just use an if
instead of a while
.
public static float mana = 1;
void Update()
{
if(mana < 100)
{
mana++;
}
}
However, this code makes the increase of the mana frame dependant. Use the following method to have a constant increase no matter the framerate:
public static float mana = 1;
public float manaIncreaseSpeed = 1; // Change this value if you want to increase / decrease the mana refill
void Update()
{
mana = Mathf.Min( mana + Time.deltaTime * manaIncreaseSpeed, 100 );
}