GUI Opener Help

Hello! I am having this problem when trying to open a GUI when you touch a part. What is supposed to happen when you touch the part, the GUI opens on the client’s screen. However, I keep getting the error Workspace.Model.Handler:14: attempt to index nil with 'TeamColor'

Here is my code:

script.Parent.TouchPart.Touched:Connect(function(char)
	local plr = game.Players:GetPlayerFromCharacter(char.Parent)
	if plr.TeamColor == BrickColor.new("Brown")  then
		if not plr.PlayerGui:FindFirstChild("UniformChangerLCSO") then
			local newUI = script.UniformChangerLCSO:Clone()
			newUI.Parent = plr.PlayerGui
			newUI.Frame:FindFirstChild("LocalScript").Disabled = false
		end
	end
end)

Just make an if statement if the player that touched the part exists.

local TouchPart = script.Parent:WaitForChild("TouchPart")

TouchPart.Touched:Connect(function(hit)
	if not hit.Parent:FindFirstChildWhichIsA("Humanoid") then
		return
	end

	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)

	if plr then
		if plr.TeamColor == BrickColor.new("Brown")  then
			if not plr.PlayerGui:FindFirstChild("UniformChangerLCSO") then
				local newUI = script.UniformChangerLCSO:Clone()
				newUI.Parent = plr.PlayerGui
				newUI.Frame:FindFirstChild("LocalScript").Disabled = false
			end
		end
	end
end)
2 Likes

Disregard my last post, it was incorrect.
But the problem is that when the part is touched, your script is automatically assuming It’s a player’s character. It could be something else.
You’ll need to add an if statement to check if the player exists:

script.Parent.Touched:Connect(function(object)
	 
	if not game.Players:GetPlayerFromCharacter(object.Parent) then	return	end
	local plr = game.Players:GetPlayerFromCharacter(object.Parent)
	
	if plr.TeamColor == BrickColor.new("Brown")  then
		if not plr.PlayerGui:FindFirstChild("UniformChangerLCSO") then
			local newUI = script.UniformChangerLCSO:Clone()
			newUI.Parent = plr.PlayerGui
			newUI.Frame:FindFirstChild("LocalScript").Disabled = false
		end
	end
end)
1 Like

+1 to this. The reason being, if a part touches your TouchPart that isn’t part of a character model, the :GetPlayerFromCharacter function won’t be able to find the player, causing it to be nil.

2 Likes