Hello, I’m a beginner developer and I want to make a script that if you press “M” on your keyboard then the audio thats playing in your game will be muted.
I’m stuck with a word in the script. What do I need to place on the question marks to make it work? (If there is anything else wrong with the script please say that too.)
Unfortunality, I cannot do that. The game is a second person shooting game. Aka, you cannot use a mouse arrow in the game. The game is obviously PC only, so I need to make keyboard functions. But thank you for your help!
First thing, I BELIEVE LocalScripts don’t work in workspace. You can put the script in StarterPlayerScripts, or StarterGui.
Solution:
Once you have re-parented the script, there’s a little something called UserInputService. You can read about it here:
UserInputService has a… connection thing (idk what to call it) known as “InputBegan”. When a player presses something on their keyboard, it will call that… connection thing.
For example:
local userInputService = game:GetService("UserInputService")
userInputService.InputBegan:Connect(function(input)
--[[ input variable is actually an instance, to get what they pressed, we need to type "input.KeyCode" --]]
if input.KeyCode == Enum.KeyCode.M then -- if they press M key, then mute
-- run the muting
end
end)
Put this code in a local script in starter player scripts.
local UIS = game:GetService("UserInputService")
local debounce = false
local music = game.Workspace:WaitForChild("Music")
UIS.InputBegan:Connect(function(input). --fires whenever they use keyboard
if input.KeyCode = Enum.KeyCode.M and debounce == false then --check if they pressed M
debounce = true
if music.Volume == 0 then
music.Volume = 1
else
music.Volume = 0
end
wait(0.5)
debounce = false
end
end)
local uis = game:GetService('UserInputService')
local music = script.Sound -- create a sound instance inside the local script
toggleMusic = function()
if music.Playing then
music:Pause()
else
music:Resume()
end
end
uis.InputBegan:Connect(function(input, isTyping)
if isTyping then return end
if input.KeyCode == Enum.KeyCode.M then
toggleMusic()
end
end)