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

Why is my random Function script activating all of the functions instead of just 1 random function?

I don't get whats happening to my script but im not sure if the problem is in the Table or the functions the scripts are below.

the table

local Table = {One ,Two ,Three ,Four ,Five}
script.Parent.MouseClick:Connect(function()
	print("Testing Testing")
	local func = Table[math.random(1,5)]
	func()
end)

and the functions. im sure the problems are in the script its just idk how to fix it.

local One = Click.MouseClick:Connect(function()
	Click.Parent = workspace.Map.Map.Dirt
	print("A")
	Button.BrickColor = BrickColor.new("Persimmon")
	wait(15)
	Button.BrickColor = BrickColor.new("Dark green")
	Click.Parent = workspace.ButtonModel.Button
end)
local Two = Click.MouseClick:Connect(function()
	Click.Parent = workspace.Map.Map.Dirt
	print("B")
	Button.BrickColor = BrickColor.new("Persimmon")
	wait(15)
	Button.BrickColor = BrickColor.new("Dark green")
	Click.Parent = workspace.ButtonModel.Button
end)
local Three = Click.MouseClick:Connect(function()
	Click.Parent = workspace.Map.Map.Dirt
	print("C")
	Button.BrickColor = BrickColor.new("Persimmon")
	wait(15)
	Button.BrickColor = BrickColor.new("Dark green")
	Click.Parent = workspace.ButtonModel.Button
end)
local Four = Click.MouseClick:Connect(function()
	Click.Parent = workspace.Map.Map.Dirt
	print("D")
	Button.BrickColor = BrickColor.new("Persimmon")
	wait(15)
	Button.BrickColor = BrickColor.new("Dark green")
	Click.Parent = workspace.ButtonModel.Button
end)
local Five = Click.MouseClick:Connect(function()
	Click.Parent = workspace.Map.Map.Dirt
	print("E")
	Button.BrickColor = BrickColor.new("Persimmon")
	wait(15)
	Button.BrickColor = BrickColor.new("Dark green")
	Click.Parent = workspace.ButtonModel.Button
end)

1 answer

✓ Accepted answer

So what you're doing is not actually creating different functions. You're basically creating 5 connections for the mouse click since you store them inside a variable, it actually runs it.

Here's how you should do it. Create your five different functions then whenever the player clicks, loop through your table of functions and choose a random function to run.

-- Variables
local func
-- Functions
local function One()
	
end

local function Two()

end

local function Three()

end

local function Four()

end

local function Five()

end
-- Tables
local myFunctionsTable = {One ,Two ,Three ,Four ,Five}
-- Connections
script.Parent.MouseClick:Connect(function()
	print("Giving a random function")
	func = myFunctionsTable[math.random(1,#myFunctionsTable)]
	func()
end)

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