Help with 'while wait'

Hi! I’m trying to script a hunger & thirst bar for a game, but only one of the two values are decreasing. I would like both to decrease simultaneously. Here’s the script:

while wait(HungerDecreaseRate) do
if HungerValue.Value - 1 >= 0 then
	HungerValue.Value = HungerValue.Value - 2
end
if HungerValue.Value == 0 then
	repeat wait(1)
		Humanoid.Health = Humanoid.Health - 5
	until HungerValue.Value > 0 or Humanoid.Health <= 0
end
end

while wait(ThirstDecreaseRate) do
if ThirstValue.Value - 1 >= 0 then
	ThirstValue.Value = ThirstValue.Value - 2
end
if ThirstValue.Value == 0 then
	repeat wait(1)
		Humanoid.Health = Humanoid.Health - 5
	until ThirstValue.Value > 0 or Humanoid.Health <= 0
end
end 

Is there something I need to do to make them both work? Help would be gladly appreciated. Thanks!

In your case, I recommend using a spawn() function. This will allow multithreading.

spawn(function()
Place your first loop in here. Your second loop should be outside and below.
end)

4 Likes

It worked. Thanks for your help!

On a separate but unrelated note, please do not use wait for the condition of a while loop. This is bad code. Use a proper condition - even putting true as the condition and then the wait statement later in the code will work fine enough.

I have a resource thread up, The While-Wait-Do Idiom, that discusses while wait loops and how they are absolutely terrible abominations of while loops (exaggerated, but you get the point).

1 Like

Just a heads up. spawn() has a wait() built into it before the code runs. If you do not that small delay to occur you could use Quenty’s NevermoreEngine fastSpawn or just alternatively use coroutines.

So:

coroutine.wrap(function()
--stuff here
end)()

It would work much better and you can have more control if you wrap these in a single poop, using DeltaTime and in line logic or clamps.

HungerRate = 2 -- hunger rates per second
ThirstRate = 2 -- thirst rate per second
HealthRate = 5 -- hp loss per second

-- returning the value of a wait gives you how much time has passed in that wait function, also called delta time. 
-- multiplying by delta tone ensures that you always (x) values per second, even if the game lags. 


while hum.Health > 0 do -- if alive
   local dt = wait(1) -- DeltaTime 

   Hunger.Value = math.clamp( Hunger.Value - HungerRate * dt, 0, 100 )
   Thirst.Value = math.clamp( Thirst.Value - ThirstRate * dt, 0, 100 )

   hum.Health = hum.Health - HealthRate * dt * ((Thirst.Value == 0 or Hunger.Value == 0) and 1 or 0)
-- the end of this code is in-line logic. If thirst or hunger is equal to 0, return a value of 1,otherwise 0,which is then multiple against the delta time,which starts / stops hp decrease
end

Considering many people don’t understand coroutine and whatever that clamp stuff is, spawn() is a good place to start.

2 Likes