- Home /
how to slow whlie down in c# code?
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++;
}
}
Answer by Hellium · Feb 17, 2020 at 05:49 PM
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 );
}
Hi Helium I really thank you. You answer is the best and isnt heavily compiled
Note the last code bit can make mana go to values above 100.0, so it may be worth clamping it to 100 again if that's not wanted.
Answer by AntoineHeseque · Feb 17, 2020 at 05:38 PM
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 ...
}
Your answer
Follow this Question
Related Questions
loop through a renderer 1 Answer
How do I stop sound from looping on button press again 1 Answer
For loop never exits 2 Answers
Making a variable editable in the inspector 1 Answer
C# Mute Button across scenes Problem 0 Answers