Hello i am a beginner at coding and I’ve made this code that plays a sound when a player touches a part but i would like the sound to be played only for the player that touched the part what changes do i need to make to be able to achieve that.
local play = false
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and play == false then
play = true
sound:Play()
wait(7)
play = false
sound:Stop()
end
end)
1 Like
Have you tried using a RemoteEvent and play the sound in a LocalScript when Remote…OnClientEvent
is fired?
I used this on a Script under the part:
play = false
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and play == false then
play = true
game.ReplicatedStorage.Event:FireClient(hit.Parent.Parent.Name)
wait(7)
play = false
end
end)
and this on a local script:
game.ReplicatedStorage.OnClientEvent:Connect(function()
Sound:Play()
wait(7)
Sound:Stop()
end)
and it didn’t work it kept saying " unable to cast value to object line:6" for the script under the part
You can record the .Touched even of the part in a local script:
local Players = game:GetService("Players")
local Client = Players.LocalPlayer
local part = -Your part address
part.Touched:Connect(function(hit)
local model = hit.Parent
local character = Client.Character
if model and character and model == character then
sound:Play()
sound.Ended:Wait()
end
end)
Would i have to delete anything from the other scripts or should i just add the one you gave me to a new local script?
Add my script to the local script
It still gives me the error unable to cast value to object for line 6 on the server script
You don’t need the RemoteEvent or server script to detect the part’s Collision.; you can rely on the client for that.
Also make sure that the sound is parented to the part.
I forgot, also the sound variable should be referenced to the part’s sound
i got it to work thank you so much
Use this:
local play = false
local sound = (your sound location here)
script.Parent.Touched:Connect(Function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr then
play = true
local s = sound:Clone
s.Parent = plr.PlayerGui
s:Play()
wait(7)
play = false
s:Stop()
s:Destroy()
end
end)
1 Like
ive made another part to test this one would this be on local or server script
1 Like
It’s for a server script.
[max char]
1 Like
it works thank you i appreciate it