Tool plays the same randomized sound when i activate it again

  1. What do you want to achieve? I want to make a tool emote that plays sounds that are randomized.

  2. What is the issue? It randomizes the sound when i activate the tool the first time, but it plays the same sound when activated the second time. I want it to play a different sound when activated again. You can see what i mean below.

https://streamable.com/guj5iw

  1. What solutions have you tried so far? Currently i did not find a solution. Here is the script!
local Tool = script.Parent
local debounce = false
local randomizing = math.random(1,6)
local handle = Tool.Handle
local sounds = handle:GetChildren()

Tool.Activated:Connect(function()
	if not debounce then
		debounce = true
		local Song = sounds[randomizing]
		Song:Play()
		wait(Song.TimeLength)
		Song:Stop()
		
		wait(7)
		debounce = false
	end
end)
2 Likes

You want a new random number each time the tool is activated.

By setting the variable at the top it’s going to stay constant, all variables retain their current value until changed. Therefore each time the tool is activated we want to change the variable to a new random number.

However we want this modular so you can add more sounds later on without having to add new lines of code or editing the script. We can do this simply, so when you get the children of the handle, you’re creating a table. We can get the length of said table by using the # operator.

Example:

local table = {"apple", "orange", "grape"}
print(#table) -- Output: 3

So how can we integrate this into our code? SImple:

randomizing = math.random(1, #sounds)

This will grab a random number between 1 and the length of the sounds table.

Your code should look like this:

local Tool = script.Parent
local debounce = false
local randomizing
local handle = Tool.Handle
local sounds = handle:GetChildren()

Tool.Activated:Connect(function()
	if not debounce then
		debounce = true
        randomizing = math.random(1, #sounds)
		local Song = sounds[randomizing]
		Song:Play()
		wait(Song.TimeLength)
		Song:Stop()
		
		wait(7)
		debounce = false
	end
end)

Hope this helped, if it did mark this as a solution so others can see it!

4 Likes

Thanks for the script, works pretty well with the tool!
now I can finally ask people to sign my petition

(note: I’m broads friend and we both work for the same game)

2 Likes

Thank you for not just solving this, but also teaching me how i can do this again without any mistake.

1 Like