Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

how do I stop food item from increasing hunger incorrectly?

I'm trying to make a survival game and so far I'm on the food system part of it. I made an apple that increases your hunger by 5 but every time I use it, It keeps going to 105 no matter what percentage the hunger is at, then if you keep eating it, it just increases the hunger further.

Hunger decrease script

local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character:WaitForChild('Humanoid')

local hunger = script.Parent.HungerBar

while wait(.5) do
	if humanoid.Health > 0 then
		if hunger.Value > 0 then
			hunger.Value = hunger.Value - 1
		else
			humanoid:TakeDamage(5)
		end
		
		local fullHunger = 1
		local currHunger = hunger.Value / 100
	else
		hunger.Value = 100
	end
end

My best guess was to put something like "If value >= 100 then value = 100" (same with 0) but I didn't know where to put it, so it only broke the script.

Tool Script

local tool = script.Parent



function onEquip()
	tool.Equip:Play()
end

function onActivate()
	wait()
	local player = game.Players:GetPlayerFromCharacter(script.Parent.Parent).PlayerGui.Bars
	local hunger = player.Hunger.HungerBar
	local thirst = player.Thirst.ThirstBar
	tool.Apple_Bite:Play()
	hunger.Value = hunger.Value + 5
	tool:Destroy()
end

tool.Activated:Connect(onActivate)

tool.Equipped:Connect(onEquip)


Is there something I'm missing on the tool script? Some sort of changed event like for the gui text to record the value?

1 answer

✓ Accepted answer

It may be because you are not checking if the player's hunger value is 100 or no. That's why it keeps increasing repeatedly even the health is at 100. You could do this in your tool script to fix this issue.

local tool = script.Parent

function onEquip()
    tool.Equip:Play()
end

function onActivate()
    wait()
    local player = game.Players:GetPlayerFromCharacter(script.Parent.Parent).PlayerGui.Bars
    local hunger = player.Hunger.HungerBar
    local thirst = player.Thirst.ThirstBar
    tool.Apple_Bite:Play()


    if hunger.Value < 100 then
            hunger.Value = hunger.Value + 5 -- Adds
    end
    
    if hunger.Value > 100 then
        hunger.Value = 100 -- Checks and makes sure that the hunger value is 100 if it goes over 100
    end

    tool:Destroy()
end

tool.Activated:Connect(onActivate)
tool.Equipped:Connect(onEquip)


3 comments

0

Thanks, that fixed the first problem but I still have a problem that makes it go back to 100 no matter what percentage of hunger it has.

0

I edited the script a bit. I think it should fix all your problem. Do you need help with the decrease script too tho?

0

nevermind, I got it to work.

This discussion is preserved as it was. New answers, comments, and votes are closed.