Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to choose a model at random to spawn?

Asked by 7 years ago

Hi there! I have a script that is supposed to choose a random number using math.random, and then when a specific number is chosen, there is an if statement of what to do about that number. (it tells a model to spawn based on what number was chosen).

Right now, there's no error, it's just choosing the last "if" statement every time (it just keeps spawning ring4) instead of adequately choosing a number or following what to do after the number is chosen, not sure which... the weirdest thing is that if I spam the button, then it gives me a number other than 4. BUT if I spawn in and press the button, like clockwork every time it chooses 4. It needs to be random, even on the first click..

01function onClicked()
02 
03local randomRing = math.random(1,4)
04 
05 
06 
07if randomRing == 1 then
08    print("RING 1")
09    game.ReplicatedStorage.rings.rings1:FireServer()
10 
11else if randomRing == 2 then
12    print("RING 2")
13    game.ReplicatedStorage.rings.rings2:FireServer()
14 
15else if randomRing == 3 then
View all 27 lines...

Thanks for your help!

1 answer

Log in to vote
1
Answered by
DeepDev 101
7 years ago

Try adding:

1math.randomseed(tick())

on the top of your script like:

01math.randomseed(tick())
02function onClicked()
03 
04local randomRing = math.random(1,4)
05 
06 
07 
08if randomRing == 1 then
09    print("RING 1")
10    game.ReplicatedStorage.rings.rings1:FireServer()
11 
12else if randomRing == 2 then
13    print("RING 2")
14    game.ReplicatedStorage.rings.rings2:FireServer()
15 
View all 28 lines...

What randomseed does is to make math.Random more random based on your current time. It may occur that a number may appear multiple times, but that will probably fix itself.

Ad

Answer this question