Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago

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

Log in to vote
2
Answered by 7 years ago

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

0
Keep it short and simple next time ^~^, cant be bother to read them all. FlaminSparrow 65 — 7y
0
No :P User#11440 120 — 7y
0
Too much informations, too lazy to read them all, so keep it short and simple pwease! ^~^ FlaminSparrow 65 — 7y
0
The answer wasn't.... No. Don't tell me how to answer questions. Thank you. User#11440 120 — 7y
Ad

Answer this question