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

How would I fix this error? Workspace.Food.Touch:6: attempt to index local 'hunger' (a nil value)

I am trying to make food eating area in my game and I made sure that the player will only eat while hunger level is below 100.

This is the error I am getting:

Workspace.Food.Touch:6: attempt to index local 'hunger' (a nil value)

This is the script that is inside of the food block:

function onTouch(hit)
	local plr = hit.Parent.Name
	local char = game.Players:FindFirstChild(plr)
	char.Backpack.Eating.Value = true
	local hunger = char.PlayerGui:FindFirstChild("Hunger")
	local hungerlevel = hunger:FindFirstChild("HungerLevel")
	if hungerlevel.Value < 100 then
	while char.Backpack.Eating.Value == true do
		char.Backpack.Food.Value = char.Backpack.Food.Value + 1
		wait(1)
	end
	end
end
script.Parent.Touched:Connect(onTouch)

4 comments

0

it means there's no "Hunger" in the playergui

0

make sure to check if the "H" in "Hunger" is capitilized

0

Basically, the output says attempt to local 'hunger' (a nil value) basically means theres no 'hunger' in the playergui

0

There is a hunger in the PlayerGui and it is capitalised.

1 answer

✓ Accepted answer

Basically, the main reason is you are trying to access the PlayerGui from the server, which isn’t possible. Instead, you should place it in a localscript, best in starter player scripts. That way the function you are trying to work upon will still continue normally while you can access the GUI.

Also, from reading the rest, I’d add an if statement in the while loop to stop them from eating too much.

Hope this helps!

6 comments

0

I've done what you said by putting the onTouch script in the food part which will then change this variable inside of the player's backpack called "Eating" to true and then the local script inside of where you said which has a while loop checking if the eating variable is equal to true and if so add 1 to food but it is not working

0

I found out that it is the while loop not working.

0

while script.Parent.Parent.Backpack.Eating.Value == true do

0

Nevermind it doesn't matter I have fixed it.

0

The server can access the PlayerGui, not just the contents of it, unless the server added the contents and they weren't there previously

0

^ I believe that the PlayerGui isn't accessible from the server compared to a Part, as it's part of the client technically, but yeah, it can't access content in it besides a server replicating them (which isn't the best practice)

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