Health Taking damage while the value is not 0 instead of it will fire when the value is 0?

Hello Developers!
Im making a game where if you ran out of hunger you will reduce health. But what happen is it reduce my health while not out of hunger. Script i created:

while wait(1) do
	if script.Parent.Value ~= 0 then
		script.Parent.Value = script.Parent.Value - 0.1
		elseif script.Parent.Value <= 0 then
		script.Parent.Parent.Humanoid.Health = script.Parent.Parent.Humanoid.Health - 1
	end
end

Thank you for the help, i really appreciate it

1 Like

One of the simplest ways to debug is to add prints every few lines or so, See what values are, what if statement activating or not

image
it stills reduce the health while the value is not 0

I assume the script is a child of the Hunger ValueObject? Assuming this, you wrote your conditional wrong.

~= means “Not”
What you need is:
== which means, “Is” or “Is Equal to”

Your script should look like this instead:

while wait(1) do
	if script.Parent.Value == 0 then
		script.Parent.Value = script.Parent.Value - 0.1
	else
		script.Parent.Parent.Humanoid.Health = script.Parent.Parent.Humanoid.Health - 1
	end
end

This way you also don’t need the “elseif” because when Hunger is anything other than 0, you don’t want to be losing health. If it’s possible that Hunger can go below 0, then you can set the conditional to be:

if script.Parent.Value <= 0 then

Which means “Less Than or Equal To”

i know that ~= means not. so if i use == it won’t reduce the player’s hunger because the starting hunger is 100.

i made it like that at my first try but it still reduces, so i put it on elseif instead.

What i’ve done is
if script.Parent.Value == 0
if script.Parent.Value <= 0
elseif script.Parent.Value == 0
if script.Parent.Value <= 0

And offtopic,
image
The bar still reduces even though the value is now 0
{
Red = health
Orange = Hunger
Blue = Thirst
}

Ohhh my bad I didn’t look at it thoroughly enough.
It might honestly be the indention. I don’t think Lua cares about formatting like that, but it may. Try moving the elseif back by one indent so that it lines up with the if. Like this:

while wait(1) do
	if script.Parent.Value ~= 0 then
		script.Parent.Value = script.Parent.Value - 0.1
	elseif script.Parent.Value <= 0 then
		script.Parent.Parent.Humanoid.Health = script.Parent.Parent.Humanoid.Health - 1
	end
end

To fix that when you set the values you could use math.clamp or something like that. Here’s how it would look:

script.Parent.Value = math.clamp(script.Parent.Value - 0.1,0,100)

the math.clamp really worked! but it stills reduces health

Try changing the ~= to > and then you can set the elseif conditional to just be else

Wait! it suddenly fixed my script! i didn’t even change anything at the script except the math.clamp and others! imma solution you since you gave me more knowledge in lua with math.clamp. Thank you!