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

Random Number Generator only produces one number. Help?

I'm working on a game that bases on chests.

What's supposed to happen is that when the chest is clicked, it spawns a random weapon.

local item1 = math.random(1, 4)

function onClicked()
	if item1 == 1 then
		local paintballGun = game.ReplicatedStorage.ClassicPaintballGun1:Clone()
		paintballGun.Parent = game.Workspace
	elseif item1 == 2 then
		local normalSword = game.ReplicatedStorage.ClassicSword1:Clone()
		normalSword.Parent = game.Workspace
	elseif item1 == 3 then
		local laserGun = game.ReplicatedStorage.LaserGun1
		laserGun.Parent = game.Workspace
	elseif item1 == 4 then
		local rpg = game.ReplicatedStorage.RPG1
		rpg.Parent = game.Workspace
	end
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

For some reason, it only spawns "laserGun", every single time. I'm not sure what to do. and when i change math.random(1, 4) to math.random(0, 4), it only spawns "normalSword". All these weapons are in ReplicatedStorage, and this script is on the chest.

1 answer

✓ Accepted answer

The problem here is that when you store the value of math.random(1,4) in local variable item1 it is taking the value of output of math.random(1,4) just once (it only runs the function once and stores the output in the variable).

What we will want to do is to generate a new random number each time the event occurs.

-- ...
function onClicked()
item1 = math.random(1,4) -- put it here.
-- ...

P.S you can make your code faster and easier to look at by using tables. Because we run the same code each time to clone a weapon and putting it in the Workspace. Here's a wiki article on the basics of how tables work. Basically when I add an entry to a table, I am assigning it a number and giving a reference to an object (just like how you have it in ReplicatedStorage).

Credit to @Paldi for the idea of using tables.

local items = game.ReplicatedStorage.Weapons:GetChildren()
-- If you put all of your weapons in a folder called Weapons then a table of the children
-- is created where each number corresponds to a different weapon.
-- you could also make this table manually.

function onClicked()
	local random = items[math.random(1,#items)] -- #items is how to see how many
	-- weapons are in the table that we are editing.
        local clone = random:Clone()
        clone.Parent = game.Workspace
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

2 comments

0

Thanks, it worked!

0

If you want to shorten calling math.random(...), you might be able to do something like "r = math.random" followed by "r(1,4)".

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