Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How would I make a script for a gun that plays audio when clicked?

I tried

local function onMouseClick(Player)
    if not Player.StarterPack:findFirstChild("ClickAudio") then 
        local ls = Instance.new("Sound")
        local length = 1 

        ls.SoundId = "http://www.roblox.com/asset/?id=337638993"
        ls.Name = "ClickAudio"
        ls.Volume = 0.5
        ls.Pitch = 1
        ls.Parent = Player.PlayerGui
        ls:Play()

        game:GetService("Debris"):AddItem(ls, length)
    end
end
script.Parent.MouseClick:connect(onMouseClick)


in the starterpack.

help, thanks

1 answer

Things in the StarterPack replicate to the Players' backpack. Also, you should use "rbxassetid://[some id]" now.

local function onMouseClick(Player)
    -- findFirstChild is deprecated, use FindFirstChild instead
    if not Player.Backpack:FindFirstChild("ClickAudio") then 
        local ls = Instance.new("Sound")
        local length = 1 

        ls.SoundId = "rbxassetid://337638993"
        ls.Name = "ClickAudio"
        ls.Volume = 0.5
        ls.Pitch = 1
        ls.Parent = Player.Backpack
        ls:Play()

        game:GetService("Debris"):AddItem(ls, length)
    end
end

script.Parent.MouseClick:Connect(onMouseClick) -- connect is deprecated, use Connect instead.

I would also suggest making more variables for things like the Debris service. It's just good practice.

After talking in chat this is the script we came up with:

--// Local Script inside tool
local tool = script.Parent
local Player = game.Players.LocalPlayer

local function onMouseClick()
    -- findFirstChild is deprecated, use FindFirstChild instead
    if not Player.Backpack:FindFirstChild("ClickAudio") then 
        local ls = Instance.new("Sound")
        local length = 1 

        ls.SoundId = "rbxassetid://337638993"
        ls.Name = "ClickAudio"
        ls.Volume = 0.5
        ls.Pitch = 1
        ls.Parent = Player.Backpack
        ls:Play()

        game:GetService("Debris"):AddItem(ls, length)
    end
end

too.Activated:Connect(onMouseClick) -- connect is deprecated, use Connect instead.

4 comments

0

the issue is im using this with a gun and when i click once, it neither makes noise nor does it shoot ever again

0

Looks like you're using a ClickDetector.

0

what would i need to do to make this work?

0

Button1Down

This discussion is preserved as it was. New answers, comments, and votes are closed.