I have a script, it's a little dated I know but I would like to keep it this way.

When you enter a brick, sound/music will start playing. When you leave a brick, it will stop. This is from putting the music into "PlayerGui." When I leave the brick, the music leaves PlayerGui, but it continues to play. It works fine when I test it, but when I start a server/go in-game it becomes a problem.

local part = script.Parent
local sound = part.Music
local plrs = game:GetService("Players")
local partsLog = {}

local function countPlr(plr)
	local n = 0
	for k, v in next, partsLog do
		if v == plr and k.Parent then
			n = n + 1
		end
	end
	return n
end

part.Touched:connect(function(hit)
	if hit and hit.Parent and plrs:GetPlayerFromCharacter(hit.Parent) then
		local plr = plrs:GetPlayerFromCharacter(hit.Parent)
		if countPlr(plr) == 0 then
			local new = sound:clone()
			new.Parent = plr:FindFirstChild("PlayerGui")
			new:Play()
		end
		partsLog[hit] = plr
	end
end)

part.TouchEnded:connect(function(hit)
	if hit and hit.Parent and plrs:GetPlayerFromCharacter(hit.Parent) then
		local plr = plrs:GetPlayerFromCharacter(hit.Parent)
		partsLog[hit] = nil
		if countPlr(plr) == 0 and plr:FindFirstChild("PlayerGui") and plr.PlayerGui:FindFirstChild(tostring(sound)) then
			plr.PlayerGui[tostring(sound)]:Stop()
			plr.PlayerGui[tostring(sound)]:Destroy()
		end
	end
end)

Does anyone know what would be causing this?

Thank you.

2 comments

0

Any errors? You should be using sound.Name

0

There's no errors. And "sound.Name" doesn't seem to make a difference. Could you elaborate any further? I appreciate your response.