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

Attempt to index local 'hit' (a nil value) ?

I've been working on this game and when you touch a certain block it detects if you have a certain gui, and if you don't you recieve the gui via :clone() The problem I'm having is, the script works, just I want the output fully cleared of errors. Don't post any answers on clearing the output.

Heres the code:

function onTouched(hit)
	hit = game.Players:GetPlayerFromCharacter(hit.Parent)
	if hit.PlayerGui:FindFirstChild("SampleGui") ~= nil then
		print("User already has menu!")
	else
		print("User recieved menu!")
		gui = game.ServerStorage.UserInterface.SampleGui:clone()
	    gui.Parent = hit.PlayerGui
	    wait(2)
	end
end

script.Parent.Touched:connect(onTouched)

I'm recieving the error: Workspace.City_Hall.SelectCityHall.Script:6: attempt to index local 'hit' (a nil value)

Please help.

1 answer

✓ Accepted answer

Make sure your code is not going to error!

At the moment, there are tons of things that could cause your script to error. Here's a list of things that could cause your script to error,

  • If a player isn't the thing that touched the script.

This is most likely the problem

... Okay that's all I found.

To make sure the part that touched the object is a player and not a part, you can do multiple things. You could,

  • Check if the part's parent has a Humanoid

  • Search for the parts parent's name in Players

  • Simply check if hit is nil

Hmmm.... There are definitely more, but that's normally what I use. I'll be using the third option.

To add a check to see if the part's parent is a player's character, here's what I would do,

function onTouched(hit)
    hit = game.Players:GetPlayerFromCharacter(hit.Parent)
	if hit then
	    if hit.PlayerGui:FindFirstChild("SampleGui") ~= nil then
	        print("User already has menu!")
	    else
	        print("User recieved menu!")
	        local gui = game.ServerStorage.UserInterface.SampleGui:clone()
	        gui.Parent = hit.PlayerGui
	        wait(2)
	    end
	end
end

script.Parent.Touched:connect(onTouched)

That makes sure the part is a child of a character. If the part's parent is the character of a player, the code will run. If not, the code will not run.

That should hopefully work, if I read your question right.

Good Luck

4 comments

0

Keep it short and simple next time ^~^, cant be bother to read them all.

0

No :P

0

Too much informations, too lazy to read them all, so keep it short and simple pwease! ^~^

0

The answer wasn't.... No. Don't tell me how to answer questions. Thank you.

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