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

How can I randomize spawning?

I have a script that I'm using coroutines in to get four NPCs to spawn at the same time. However, because I include this line in my code:

local activeNPCs = workspace.ActiveNPCs
local spawns = workspace.Spawns:GetChildren()

local function spawnNPC()
	local NPCs = game:GetService("ReplicatedStorage").AvailableNPCs:GetChildren()
	local randomNPC = NPCs[math.random(1,#NPCs)]
	randomNPC.Parent = game:GetService("ReplicatedStorage").UnavailableNPCs
	local newNPC = randomNPC:clone()
	newNPC.Parent = activeNPCs
	print(spawns[math.random(1, #spawns)])
	newNPC:MoveTo(spawns[math.random(1,#spawns)].Position)
	local newForceField = Instance.new("ForceField",newNPC)
	game:GetService("Debris"):AddItem(newForceField, 10)
end

for _ = 1,4 do
	spawnNPC()
	wait()
end

I am unable to randomize spawning. So, how exactly does math.random work? I'm guessing that math.random is equal to a certain number at any given time, so when four functions are fired at the same time, the math.random value is the same. How can I randomize this?

1 answer

✓ Accepted answer

After 30 minutes of working at this, I could not get the randomized spawn because I'm too pro.

But anyways, I've made a script that'll basically goes through the spawns and spawn the NPC's there. This will make them spawn at different places, but it's not randomized.

End result:

local activeNPCs = workspace.ActiveNPCs
local spawns = workspace.Spawns:GetChildren()

local function spawnNPC(spawn)
    local NPCs = game:GetService("ReplicatedStorage").AvailableNPCs:GetChildren()
    local randomNPC = NPCs[math.random(1,#NPCs)]
    randomNPC.Parent = game:GetService("ReplicatedStorage").UnavailableNPCs
    local newNPC = randomNPC:clone()
    newNPC.Parent = activeNPCs
    newNPC:MoveTo(spawn.Position)
    local newForceField = Instance.new("ForceField",newNPC)
    game:GetService("Debris"):AddItem(newForceField, 10)
end

for i = 1, #spawns do
local RandomSpawn = spawns[i]
spawnNPC(RandomSpawn)
end

Hoped this helped somewhat, due to me not figuring out how to randomize the spawns.

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