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..

function onClicked()

local randomRing = math.random(1,4)



if randomRing == 1 then
    print("RING 1") 
    game.ReplicatedStorage.rings.rings1:FireServer()

else if randomRing == 2 then
    print("RING 2") 
    game.ReplicatedStorage.rings.rings2:FireServer()

else if randomRing == 3 then
    print("RING 3") 
    game.ReplicatedStorage.rings.rings3:FireServer()

else if randomRing == 4 then
    print("RING 4") 
    game.ReplicatedStorage.rings.rings4:FireServer()
end
end
end
end
end
script.Parent.MouseButton1Down:connect(onClicked)

Thanks for your help!

1 answer

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

Try adding:

math.randomseed(tick())

on the top of your script like:

math.randomseed(tick())
function onClicked()

local randomRing = math.random(1,4)



if randomRing == 1 then
    print("RING 1") 
    game.ReplicatedStorage.rings.rings1:FireServer()

else if randomRing == 2 then
    print("RING 2") 
    game.ReplicatedStorage.rings.rings2:FireServer()

else if randomRing == 3 then
    print("RING 3") 
    game.ReplicatedStorage.rings.rings3:FireServer()

else if randomRing == 4 then
    print("RING 4") 
    game.ReplicatedStorage.rings.rings4:FireServer()
end
end
end
end
end
script.Parent.MouseButton1Down:connect(onClicked)

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