It's been a while since I have last scripted (up to around a year) and now trying to get back into it by developing the script below. This script is placed under a transparent, CanCollide = false, sphere part. What I am trying to do is when the character is no longer touching the part (or within the sphere part), the volume of the sound decreases to 0 and then the sound pauses. I don't know what I am doing wrong. Perhaps someone can provide useful insight.
function onTouch(hit)
local px = hit.Position.X
local rx = script.Parent.Position.X
local py = hit.Position.Y
local ry = script.Parent.Position.Y
local pz = hit.Position.Z
local rz = script.Parent.Position.Z
local tx = math.abs((px)-(rx))
local ty = math.abs((py)-(ry))
local tz = math.abs((pz)-(rz))
local z = game.Players:GetPlayerFromCharacter(hit.Parent)
if tx > 20 then
print("tx is" .. tx)
for i=0, 1, 0.1 do
wait(0.2)
z.PlayerGui.Sound.Volume = (z.PlayerGui.Sound.Volume)-0.1
end
z.Parent.Parent.Sound:Pause()
end
if ty > 20 then
print("ty is" .. ty)
for i=0, 1, 0.1 do
wait(0.2)
z.PlayerGui.Sound.Volume = (z.PlayerGui.Sound.Volume)-0.1
end
z.Parent.Parent.Sound:Pause()
end
if tz > 20 then
print("tz is" .. tz)
for i=0, 1, 0.1 do
wait(0.2)
z.PlayerGui.Sound.Volume = (z.PlayerGui.Sound.Volume)-0.1
end
end
end
script.Parent.Touched:connect(onTouch)

2 comments
I think the error lies near the bottom-half of the script
Make sure that this is in a localscript, a normal (server) script cannot access PlayerGui.