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

Why math.random is unreal random?

local pathpart = workspace.IslandParts.islandpaths.islandpath

for i,pathpart in pairs(pathpart.Parent:GetChildren()) do
	
	if pathpart.Name == "islandpath" then

		local palmgen= math.random(30)
		if palmgen == 2  then
			print("PALM GEN IS: ",palmgen)
			local palm = game.ReplicatedStorage.Assets.islandnature.palm:Clone()
			palm.Parent = workspace
			palm:MoveTo(pathpart.Position)
			
		else
			print("PLAM GEN IS: ",palmgen)
		end
	end

end

Facilities should create a random object if palmgen = 2, but math.random ALWAYS produces the same random numbers. How to make this feature really random?

1 comment

1

math.random uses a seed to calculate its 'random' output. In studio, the seed doesn't update when you test it again and again. It will be different in an actual game, though.

1 answer

✓ Accepted answer

You need to warm the pseudo random generator by using math.randomseed(x). Where x is the seed for the generator. One of the most common ways for warming it up is to use tick() as the input. Applying this to your script would make it into.

local pathpart = workspace.IslandParts.islandpaths.islandpath
math.randomseed(tick())

for i,pathpart in pairs(pathpart.Parent:GetChildren()) do

    if pathpart.Name == "islandpath" then

        local palmgen= math.random(30)
        if palmgen == 2  then
            print("PALM GEN IS: ",palmgen)
            local palm = game.ReplicatedStorage.Assets.islandnature.palm:Clone()
            palm.Parent = workspace
            palm:MoveTo(pathpart.Position)

        else
            print("PLAM GEN IS: ",palmgen)
        end
    end

end

1 comment

1

Important fact about randomseed: you only ever want to use it once or 0 times. Setting it too often can result in extremely biased results, as it 'reboots' the RNG algorithm, which is only non-biased over a long period of time.

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