I am trying to write a code to change the SoundId of a Sound Instance for a player depending on whether they touch a block or not. However, I do not want the SoundId to be changed if the correct Sound is already playing for a player. I used a remote event to ensure that the correct song is only playing for the client (Player) and not the server. However, the SoundId of the song playing for the player does not seem to change which results in the remoteEvent being fired several times. Why does this happen?
LocalScript for the RemoteEvent
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage.PlayMusic
local player = Players.LocalPlayer
local function changeMusic(newSong)
local song1 = player.Songs.CurrentlyPlaying:FindFirstChildOfClass("Sound")
if song1 then
song1:Stop()
song1:Destroy()
song1 = Instance.new("Sound", player.Songs.CurrentlyPlaying)
song1.SoundId = newSong.SoundId
song1:Play()
else
warn("Currently playing song not found.")
end
end
remoteEvent.OnClientEvent:Connect(changeMusic)
Script for the RemoteEvent
local mySong = script.Parent:FindFirstChildOfClass("Sound")
local musicBox = script.Parent
local players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage.PlayMusic
musicBox.Touched:Connect(function(hit)
local char = hit.Parent:FindFirstChild("Humanoid")
if char then
local plr = players:GetPlayerFromCharacter(char.Parent)
if plr then
local currentlyPlaying = plr.Songs.CurrentlyPlaying.Sound
local mySong = musicBox:FindFirstChildOfClass("Sound")
if mySong then
print("Song 1: ", currentlyPlaying and currentlyPlaying.SoundId, "\nSong 2: ", mySong.SoundId)
if currentlyPlaying.SoundId ~= mySong.SoundId then
remoteEvent:FireClient(plr, mySong)
end
wait()
currentlyPlaying = plr.Songs.CurrentlyPlaying
else
warn("No sound found in musicBox")
end
end
end
end)
the Sound Instance created by the client doesn't replicate to the server