Noob programmer here,
I was making a music-area script, it’s work in progress.
I was making it stop playing an audio when a hitbox-part is touched, and it was a local script.
local function Play()
game.Workspace.MusicDisc.Chirp.Volume = 0
end
game.Workspace.SpecialSongPart.Touched:Connect(Play()
It doesn’t give me any errors, but the code doesn’t work. I tried running the script as a normal script (not local) and it still doesn’t work. How can I fix this? (try to keep it simple please, I barely know how to code.)
This should be enough code to help you understand the proper practices of the Touched event, in this you will see many uses of the Instance functions.
When using RBXScriptSignal:Connect, make sure you support the function’s variable, not the function’s response.
I noticed that issue so I’ll write this below to help you understand it more.
-- Function response:
RBXScriptSignal:Connect(myFunction()) -- Connects the function's response, not the function.
-- Function variable:
RBXScriptSignal:Connect(myFunction) -- Connects the function's value, because it's the variable and only the variable.
local BasePart = workspace:WaitForChild("SpecialSongPart")
local MusicDisc = workspace:WaitForChild("MusicDisc")
BasePart.Touched:Connect(function(HitInstance)
if HitInstance:FindFirstAncestorWhichIsA("Accoutrement") or HitInstance:FindFirstAncestorWhichIsA("BackpackItem") then
return
end
local Character = HitInstance:FindFirstAncestorWhichIsA("Model")
local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
if Humanoid:GetState() ~= Enum.HumanoidStateType.Dead and Humanoid.Health > 0 then
local Chirp = MusicDisc:WaitForChild("Chirp")
Chirp.Volume = 0
Chirp:Stop()
end
end)
Then you should use .magnitude for this. It’s actually more reliable and you can also use this increase the volume when the player moves away from the hitbox part.
Example:
game:GetService("RunService").Heartbeat:Connect(function()
local Magnitude = (game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart").Position - game.Workspace:WaitForChild("YourHitBoxPartNameHere").Position).Magnitude
if Magnitude <= 10 then --Depending on your part size.
game.Workspace.MusicDisc.Chirp.Volume = 0
-- else
-- game.Workspace.MusicDisc.Chirp.Volume = 0.5 (You can also use this to increase the volume when the player is far away from the part)
end
end)
Thank you, this helped me understand better. But honestly reading all this I feel like I should just learn more coding first, this seems way too advanced for me. Nevertheless, thank you for the help!
Thank you, this helped me understand better. But honestly reading all this I feel like I should just learn more coding first, this seems way too advanced for me. Nevertheless, thank you for the help! !