How to play a sound from a morph using a GUI button

Hey there. So I am trying to make a morph for my game, and it will include sounds that you can play by clicking a GUI button. I added a remote event to go with the function so all players can hear the sound. The sound will be kept inside of the Morph’s HumanoidRootPart so players can hear the sound from a radius. Here are the scripts.

Morph Script (Proximity Prompt Function)

local model = script.Parent
local prompt = workspace.NoobMorphPart.ProximityPrompt

prompt.Triggered:Connect(function(player)
	local oldCharacter = player.Character
	local morphModel = workspace.Noob
	local newCharacter = morphModel:Clone()

	newCharacter.HumanoidRootPart.Anchored = false
	newCharacter:SetPrimaryPartCFrame(oldCharacter.PrimaryPart.CFrame)

	player.Character = newCharacter
	newCharacter.Parent = workspace
	

	script.Parent.SoundGUI:Clone().Parent = player.PlayerGui
end)

Local Script (GUI Button) :

local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")

local function PlaySound()
	Event:FireServer()
end

script.Parent.MouseButton1Down:Connect(PlaySound)

Server Script (Replicated Storage) :

local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")
local Sound = game.Players.LocalPlayer.Character.HumanoidRootPart.Sound

Event.OnServerEvent:Connect(function(Player)
	Sound:Play()
end)

Every time I click the button, it will give me this error message: ServerScriptService.ServerScript:2: attempt to index nil with 'Character’

I can provide more information if needed. How should I go about fixing this?

1 Like

game.Players.LocalPlayer can only be used in LocalScript

Oh okay. What should I do instead?

1 Like

ServerScript

local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")

Event.OnServerEvent:Connect(function(Player)
	local character = Player.Character
    local sound = character.HumanoidRootPart:FindFirstChild("Sound")
    if sound then
       sound:Play()
    end
end)

Thanks. I’ll have to try this a little later. If this works, I will be very thankful!

1 Like

It works! Thanks a lot! You have no idea how much this helps me out.

You also need to check for the character and the rootpart, because this will error

local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")

Event.OnServerEvent:Connect(function(Player)
	local character = Player.Character
    local sound = character and character:FindFirstChild("HumanoidRootPart") and character.HumanoidRootPart:FindFirstChild("Sound")
    if sound then
       sound:Play()
    end
end)

bad fix but it should work and stop the error

1 Like