Script working, but giving errors

When a part is touched, I want a GUI to pop up showing the control for sprinting. To do this is have a part, and inside it is a server script and the GUI I would like to appear. When the part is touched, the script moves the GUI into PlayerGui and deletes the part.
This all works fine, but there is an error on line 3 saying ‘attempt to index nil with Parent’
Here is the code:

script.Parent.Touched:Connect(function(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
	local plr = game.Players:GetPlayerFromCharacter(h.Parent) 
	script.Parent.Sprint.Parent = plr.PlayerGui
	wait(0.01)
	script.Parent:Destroy()
end)

Does anyone know how I can stop this error appearing?

Do this

script.Parent.Touched:Connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	if not plr then return end
	script.Parent.Sprint.Parent = plr.PlayerGui
	wait(0.01)
	script.Parent:Destroy()
end)

why do you have to parent it to the player? can you just already have it in startGui and just enable and disable it? And the probably means it did not find h. Just do a check

if not hit.Parent:FindFirstChild("Humanoid") then return end --the hit is not a player

That worked, thank you for the help

1 Like

I am more familiar with the method of parenting Gui’s to PlayerGui through the Touched function in server scripts…I have a weird way of programming