Math.random keep on giving me the same thing

Hello, so im trying to choose a random object from a folder using math.random but it keeps on giving me the exact same object here is my script:

local Folder = game.ReplicatedStorage.Folder
local rfolder = Folder:GetChildren()
local chosenPet = rfolder[math.random(1, #rfolder)]
local player = game.Players.LocalPlayer
game.ReplicatedStorage.RemoteEvent.OnClientEvent:Connect(function()
	script.Parent.Visible = true
	chosenPet:Clone().Parent = player.Inventory
	script.Parent.TextLabel.Text = chosenPet.Name
	wait(1)
	script.Parent.Visible = false
end)

Thank you!

1 Like

Generate a random number within the callback you pass to RemoteEvent.OnClientEvent, so that a random object is selected from the array each time - in its current working, only a random object will be selected at the beginning and when the callback executes, the same object would be cloned each time the event fires unless the math.random call at the beginning runs again to produce a different result.

In short: move this line

local chosenPet = rfolder[math.random(1, #rfolder)]

to after this line

game.ReplicatedStorage.RemoteEvent.OnClientEvent:Connect(function()
3 Likes

Thank you its working now (30 characters)

You set the randomised pet to be declared before you called the event, meaning it is a fixed value all the way through.

@XxELECTROFUSIONxX’s solution is spot on.

1 Like