Math.random not returning random number

Trying to make a random spawn system where a random number gets assigned to a different spawn, then an npc spawns there. Only issue is that the random number only changes once. obivously thats an issue cause i want different spawns, not the same one every time.

CODE:

event.Zombies = function(zombAmount, duration)
	local spawnFolder = game.Workspace:WaitForChild("zombieSpawns")
	
	for i = 1, zombAmount, 1 do
		print(i)
		local zomb = models:WaitForChild("Zombie"):Clone()
		local rSpawn = math.random(1, #spawnFolder:GetChildren())
		print(rSpawn)
		zomb:SetPrimaryPartCFrame(spawnFolder:FindFirstChild(rSpawn).CFrame)
		zomb.Parent = game.Workspace.Zombies
	end	
	
	task.spawn(function()
		wait(duration)
		
		for i, v in pairs(game.Workspace.Zombies:GetChildren()) do
			if v.ClassName == "Model" and v.Name == "Zombie" then
				v:Destroy()
			end
		end
	end)
end

thanks,
dza

You could do math.randomseed(tick()) every time your for loop runs.

1 Like

it now returns argument 1 missing or nil

No, put the math.randomseed(tick()) one line before the math.random().

just tested it now and now it only returned 2 different numbers instead of the one

Does the Workspace:WaitForChild("zombieSpawns") have more than 1 object inside of it? If not, this line would be: math.random(1, 1) which outputs 1.

And if it doesn’t, are there any spawnFolder variables that override this value?

There are 36 objects in the folder and the code i sent is essentially the only thing that’s there in the module script

Where you have the print(i) instead do print(#spawnFolder:GetChildren()).
And when does this get fired?

the print statement returns 36, the function gets called in a different script in serverscriptservice where every x amount of seconds it gets called since it’s like an event that’s supposed to happen in my game.

I should probably mention that the random number does change every time the code runs, but during the for loop when it’s supposed to change, it doesn’t

Maybe you can use the built-in Random Datatype instead.

This datatype also has a built-in keyword itself. First, we need to create a seed for the constructor Random.new()

local rand = Random.new(100)

Then, we can use rand:NextInteger() to get a random integer from a min and max value.

for i = 1, zombAmount, 1 do
	local rSpawn = rand:NextInteger(1, #spawnFolder:GetChildren())
end
2 Likes

how have i never heard of the Random datatype after being on here for 2+ years :sob:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.