Playing a sound serverside from a client variable

i have a NumberValue called ‘fear’ inside starterplayerscripts and depending on events occuring in the game the value changes between 50 and 100.I want to make a breathing sound play from the character of the player thats fear value is equal to or above 80 and make it so everyone who is close enough to the player can hear it, how can i achieve that?

1 Like

Hi @sozenss ,

To do what you are asking you would most likely need to have to check when the “fear value” is over 80 within the local script (since the value is local) and than if it is over 80 fire a event to the server to play the sound.

1 Like

Is this value changed on the client or on the server?

1 Like

the value is changed on the client

You’ll need to create a RemoteEvent to signal to the server when to play the sound.

1. Create the RemoteEvent
In ReplicatedStorage, create a RemoteEvent named FearValueChanged.

2. Create the Client Script (StarterPlayerScripts)

LocalScript (StarterPlayerScripts)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

local player = Players.LocalPlayer
local fearValue = script.Parent:WaitForChild("Fear") -- Assuming Fear shares the same parent

-- Ensure the RemoteEvent exists
local remoteEvent = ReplicatedStorage:FindFirstChild("FearValueChanged")
if not remoteEvent then
     error('REMOTE EVENT WAS NOT CREATED.')
end

local function onFearValueChanged(newValue)
    if newValue >= 80 then
        remoteEvent:FireServer(newValue)
    end
end

fearValue:GetPropertyChangedSignal("Value"):Connect(function()
    onFearValueChanged(fearValue.Value)
end)

3. Server Script (ServerScriptService)

Script (ServerScriptService)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

local remoteEvent = ReplicatedStorage:WaitForChild("FearValueChanged")

local function playBreathingSound(player)
    local character = player.Character
    if character then
        local sound = Instance.new("Sound", character)
        sound.SoundId = "rbxassetid://<your-sound-id>" -- Replace with your sound ID
        sound.Looped = true
        sound.Volume = 1
        sound:Play()
        
        -- Adjust sound range if needed
        sound.EmitterSize = 10 -- Adjust as needed
        sound.MaxDistance = 100 -- Adjust as needed
        
        -- Cleanup sound after some time if necessary
        delay(10, function()
            sound:Destroy()
        end)
    end
end

remoteEvent.OnServerEvent:Connect(function(player, fearValue)
    if fearValue >= 80 then
        playBreathingSound(player)
    end
end)

Make sure to replace <your-sound-id> with the actual sound ID you want to use.

1 Like

thanks you bro it works now. Take care

1 Like