Attempt to index nil with 'destroy' but the script still works

Here is a script for a shop part that activates a gui when stepped on and deactivates when a remote event is fired or it’s stepped off of. (credit to @4467hp)

local Players = game:GetService("Players")
local Part = script.Parent

Part.Touched:Connect(function(Hit)
	local Player = Players:GetPlayerFromCharacter(Hit.Parent)
	if not Player then return end

	if not Player.PlayerGui:FindFirstChild("GUIClonedfromtouchblock") then
		local Clonedgui = script.Parent:FindFirstChildOfClass("ScreenGui"):Clone()
		Clonedgui.Name = "GUIClonedfromtouchblock"
		Clonedgui.Parent = Player.PlayerGui
	end
end)

Part.TouchEnded:Connect(function(Hit)
	local Player = Players:GetPlayerFromCharacter(Hit.Parent)
	if not Player then return end

	local Ui = Player.PlayerGui:FindFirstChild("GUIClonedfromtouchblock")
	Ui:Destroy()
end)

local storage = game:GetService("ReplicatedStorage")
local event = storage.exit
event.OnServerEvent:Connect(function(player)

	local ui = player.PlayerGui:FindFirstChild("GUIClonedfromtouchblock")
	ui:Destroy()
end)

The script works as expected, but I get the error anyway. In my experience, this usually completely stops the script from working so it’s a bit odd. Is it something I should be worried about?

You should add if ui then as the ui could be nil.

local Players = game:GetService("Players")
local Part = script.Parent

Part.Touched:Connect(function(Hit)
	local Player = Players:GetPlayerFromCharacter(Hit.Parent)
	if not Player then return end

	if not Player.PlayerGui:FindFirstChild("GUIClonedfromtouchblock") then
		local Clonedgui = script.Parent:FindFirstChildOfClass("ScreenGui"):Clone()
		Clonedgui.Name = "GUIClonedfromtouchblock"
		Clonedgui.Parent = Player.PlayerGui
	end
end)

Part.TouchEnded:Connect(function(Hit)
	local Player = Players:GetPlayerFromCharacter(Hit.Parent)
	if not Player then return end

	local Ui = Player.PlayerGui:FindFirstChild("GUIClonedfromtouchblock")
	if Ui then
		Ui:Destroy()
	end
end)

local storage = game:GetService("ReplicatedStorage")
local event = storage.exit
event.OnServerEvent:Connect(function(player)

	local ui = player.PlayerGui:FindFirstChild("GUIClonedfromtouchblock")
	
	if ui then
		ui:Destroy()
	end
end)

2 Likes

Check if the ui is nil before destroying it.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.