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

math.random keeps choosing the same id?

This script below is suppose to insert the ids into a table, in which it does but if you play the game online it keeps picking the same ID if you use math.random.

NOTE: This is in a module script.

for i, id in pairs(require(script.musiclist)) do -- Sets up the music table, :)
		table.insert(songs, id)
		local ContentProvider = game:GetService("ContentProvider")
		ContentProvider:Preload("rbxassetid://"..id) --Preload whatever asset(s) you need.
		WaitForAssetsToLoad()
		print("Songs loaded...")

		local pickSong = songs[math.random(1, #songs)]
		print(pickSong)
	end	

This is a picture of the list of IDs:

http://prntscr.com/cj8x84

1 comment

0

It ALWAYS picks : 315664700 in online mode.

1 answer

✓ Accepted answer

Your problem is the script runs in an order, and while it is called math.random, it will pick the same number every time unless you do something about it. This is because of the fact that math.random relies on the previous number in order to get the next one. Since there is no previous at the beginning, it will always start off at the same number...

Which is where math.randomseed() comes in

What does this do?

This handy little function allows for the beginning of the script that will randomize the first number used in math.random

How can I randomize this in my script

Well, the only thing that changes constantly in Lua is tick(). That is the number of seconds since Epoch.

math.randomseed(tick())

By doing this, we can guarantee that the first number will not be picked every time it is tested.

Here is your final script:

math.randomseed(tick())

for i, id in pairs(require(script.musiclist)) do -- Sets up the music table, :)
        table.insert(songs, id)
        local ContentProvider = game:GetService("ContentProvider")
        ContentProvider:Preload("rbxassetid://"..id) --Preload whatever asset(s) you need.
        WaitForAssetsToLoad()
        print("Songs loaded...")

        local pickSong = songs[math.random(1, #songs)]
        print(pickSong)
    end 

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