Math.random doesn't work properly

So, I have to make a script where it will randomly decide which function will be called, but for some reason it will only call the function that has to be called if 1 will be chosen by math.random, and functions under other numbers will not call the function or any other action, and instead just skip it onto next lines.
The code is:

local values = game.Workspace.MetroMap.Part1.Area2.Values

local sa1p = game.Workspace.MetroMap.Part1.Area2.TouchParts.ShopArea1Part

local light = script.Parent.SurfaceLight

local angle = light.Angle

local neon = script.Parent

local anglevalue = script.Parent.SurfaceLight.AngleNum.Value

local function disable()
	

	neon.Material = Enum.Material.SmoothPlastic

	light.Enabled = false

	light.Angle = 0
	
	sa1p.LampsSound2:Stop()
	
	end

local function enable()
	
	local mr1 = math.random(1,3)
	
	local function enable1()
		
		sa1p.LampsSound2:Play()

		neon.Material = Enum.Material.Neon

		light.Enabled = true

		light.Angle = 22.5

	end
	
	local function enable2()
		
		sa1p.LampsSound1:Play()
		
		local function angletween()

			local tw = game:GetService("TweenService")

			local twi = TweenInfo.new(
				2,
				Enum.EasingStyle.Back
			)

			local angletw = tw:Create(light, twi, {Angle = anglevalue})

			angletw:Play()

		end

		neon.Material = Enum.Material.Neon

		light.Enabled = true

		angletween()

	end
		
	local function rng1()
			
		enable1()
		wait(0.15)
		disable()
		wait(0.15)

		end
		
	local function rng2()

			enable1()
			wait(0.25)
			disable()
			wait(0.15)

		end
		
	local function rng3()

			enable1()
			wait(0.5)
			disable()
			wait(0.15)

	end
	
	local function rngenable()
		
		if mr1 == 1 then rng1()

			if mr1 == 2 then rng2()

				if mr1 == 3 then rng3()

				end
			end
		end
		
		end
	
	rngenable()
	
	enable2()
	
	end

values.A1Lamp1Power.Changed:Connect(function(Value)
	
	if Value == true then
		
		enable()
	else
		disable()
		
	end
	
end)

What I need is functions to be called if number other than 1 will be chosen.

1 Like

math.random is very weird i suggest you use Random.new()

local random = Random.new()

local int = random:NextInteger(1, 3)
local float = random:NextNumber(0.1, 3.9

Use the formatter before pasting code, it will automatically fix indentation.
image

The problem is you are using nested if statements instead of if/elseif/else. All of these ifs are checked one after another, if mr1 == 1 fails it will skip the whole block. You end up either getting rng1 or nothing.

-- formatted your code to better show the order of events
if mr1 == 1 then
	rng1()
	if mr1 == 2 then -- skipped if mr1 ~= 1
		rng2()
		if mr1 == 3 then -- skipped if mr1 ~= 1
			rng3()
		end
	end
end

This code will check 1, 2, and 3

if mr1 == 1 then
    rng1()
elseif mr1 == 2 then
    rng2()
elseif mr1 == 3 then
    rng3()
end
1 Like

Oh well thank you. It is working now, and also thank for hinting how to properly past code.