Attempt to index nil with 'PlayerGui'

Heyyy, I have a problem with a script, however! this one works! but each time, I get an error that appears: attempt to index nil with ‘PlayerGui’

The Script :

local part = script.Parent
local debounce = false

part.Touched:Connect(function(hit)
		local char = hit.Parent
		local plr = game.Players:GetPlayerFromCharacter(char)

		plr.PlayerGui.ActivateButton.Bar:TweenPosition(UDim2.new(0.5, 0,0.258, 0),Enum.EasingDirection.Out, Enum.EasingStyle.Linear, true)
	end)
part.TouchEnded:Connect(function(hit)
		
		local char = hit.Parent
		local plr = game.Players:GetPlayerFromCharacter(char)
		
		plr.PlayerGui.ActivateButton.Bar:TweenPosition(UDim2.new(1.5, 0,0.258, 0),Enum.EasingDirection.Out, Enum.EasingStyle.Linear, true)
	end)

index nil with ‘PlayerGui’ means you are trying to get nil.PlayerGui.

...
local plr = game.Players:GetPlayerFromCharacter(char)
plr.PlayerGui ...

The error says plr is nil.
To silence the error, make the function do nothing if plr is nil.

local part = script.Parent
local debounce = false

part.Touched:Connect(function(hit)
	local char = hit.Parent
	local plr = game.Players:GetPlayerFromCharacter(char)
	if plr == nil then return end -- added

	plr.PlayerGui.ActivateButton.Bar:TweenPosition(UDim2.new(0.5, 0,0.258, 0),Enum.EasingDirection.Out, Enum.EasingStyle.Linear, true)
end)
part.TouchEnded:Connect(function(hit)
	local char = hit.Parent
	local plr = game.Players:GetPlayerFromCharacter(char)
	if plr == nil then return end -- added
	
	plr.PlayerGui.ActivateButton.Bar:TweenPosition(UDim2.new(1.5, 0,0.258, 0),Enum.EasingDirection.Out, Enum.EasingStyle.Linear, true)
end)
4 Likes

It’s working! Thx!!!

Also, this is not directly related to the issue, but you are trying to work with TouchEnded, which is notoriously hard to tame. TouchEnded will fire when just one part of the character stops touching the part, which can make the GUI pop in and out in very strange ways sometimes.

To mitigate this, make sure the HumanoidRootPart can touch part, and make the functions not continue if they’re not touching it.

if plr == nil or hit.Name ~= "HumanoidRootPart" then return end

The chosen part doesn’t need to be HumanoidRootPart. It could be the Head or something. What’s important is that only one part of the player can trigger it, so that each player can have only one part of their character influencing the GUI.
Again, this isn’t super important, just something to fix a potential ugly glitch.

1 Like

Okayy! thanks for this information!