So here's my script
Var1 = math.random(1,3) function clicked() if Var1 == 1 then Instance.new("Part",game.Workspace) elseif Var1 == 2 then Instance.new("TrussPart",game.Workspace) elseif Var1 == 3 then Instance.new("ParticleEmitter",game.Workspace) else print("Nothing has happen") end end script.Parent.ClickDetector.MouseClick:Connect(clicked)
Whenever I start the "Play" I click the clickdetector and only spawns only one of the random 3 parts.. like if I started the game and then spammed clickdetector it would only do number 2 which would be TrussPart and another time when I press "Play" it would spawn number 1 which is Part.
How can I do it so whenever I press the Clickdetector it makes it so that it chooses 1,2 or 3 randomly instead of being stuck on one of the numbers.
Because the math.random is outside the function it only fires once, you need it to fire everytime to give a new number so make it fire when the function is fired.
function clicked() Var1 = math.random(1,3) if Var1 == 1 then Instance.new("Part",game.Workspace) elseif Var1 == 2 then Instance.new("TrussPart",game.Workspace) elseif Var1 == 3 then Instance.new("ParticleEmitter",game.Workspace) else print("Nothing has happen") end end script.Parent.ClickDetector.MouseClick:Connect(clicked)
math.random() usage is now discouraged, because even since it was re-implemented with to use the new PRNG, it's using a shared instance, so even when seeded you can't make it deterministic for testing and debugging purposes. It also redirects to the new Random class through a bunch of conditional logic in order to support all the variants of arguments math.random() could take and map them to the new calls. So better off to just use the new system yourself.
It's not more any more lines of code because the constructor is the randomseed function, and you use it basically the same way once you have an instance of the generator.
Example:
local TYPES = { "Part", "TrussPart", "ParticleEmitter" } local RNG = Random.new(tick()) -- Constructs and seeds the PRNG local function Clicked() Instance.new(TYPES[RNG:NextInteger(1,3)], game.Workspace) end script.Parent:FindFirstChildOfClass("ClickDetector").MouseClick:Connect(Clicked)
I've also removed the unnecessary use of conditional logic and comparisons to index into a finite set of options.