Is there any way to make this loop take less time?

I’m attempting to make a round system that spawns a bunch of dummys with player appearances from your friends list, everything works fine but it takes so long. Players should not have to wait this long to enter a round, is there any way to make this take less time?

Here’s the code

function spawnpeople()
	for i = peopleamount - cloneamount, 1, -1 do
		theloop()
	end
	game.ReplicatedStorage.Events.ScreenFinish:Fire()
end

function theloop()
	local dummy = game.ReplicatedStorage.Base:Clone()
	randomfriend = ids[math.random(1, #ids)]
	local username = players:GetNameFromUserIdAsync(randomfriend)
	if not table.find(usernames, username) then
		table.insert(usernames,username)
	else
		theloop()
		return
	end
	print(usernames)
	if not randomfriend then
		print("No friends haha")
	end
	description = players:GetHumanoidDescriptionFromUserId(randomfriend)
	local randomspawn = game.Workspace.Map:WaitForChild(maptype..peopleamount).Spawns:GetDescendants()
	local dummyspawn = randomspawn[math.random(1, #randomspawn)]
	humanoid = dummy.Humanoid or dummy:FindFirstChild("Humanoid") 

	dummy.Parent = game.Workspace.Persons
	dummy:WaitForChild("HumanoidRootPart").CFrame = dummyspawn.CFrame
	dummy.Name = players:GetNameFromUserIdAsync(randomfriend)
	local typeis = dummy.Values:WaitForChild("Type")
	typeis.Value = "Person"
	dummyspawn:Destroy()
	humanoid:ApplyDescription(description)
end
1 Like

getting the humanoiddescription and other stuff is probably yielding the code, try spawning the function in a new thread with task.spawn

function spawnpeople()
	for i = peopleamount - cloneamount, 1, -1 do
		task.spawn(theloop)
	end
	game.ReplicatedStorage.Events.ScreenFinish:Fire()
end

function theloop()
	local dummy = game.ReplicatedStorage.Base:Clone()
	randomfriend = ids[math.random(1, #ids)]
	local username = players:GetNameFromUserIdAsync(randomfriend)
	if not table.find(usernames, username) then
		table.insert(usernames,username)
	else
		theloop()
		return
	end
	print(usernames)
	if not randomfriend then
		print("No friends haha")
	end
	description = players:GetHumanoidDescriptionFromUserId(randomfriend)
	local randomspawn = game.Workspace.Map:WaitForChild(maptype..peopleamount).Spawns:GetDescendants()
	local dummyspawn = randomspawn[math.random(1, #randomspawn)]
	humanoid = dummy.Humanoid or dummy:FindFirstChild("Humanoid") 

	dummy.Parent = game.Workspace.Persons
	dummy:WaitForChild("HumanoidRootPart").CFrame = dummyspawn.CFrame
	dummy.Name = players:GetNameFromUserIdAsync(randomfriend)
	local typeis = dummy.Values:WaitForChild("Type")
	typeis.Value = "Person"
	dummyspawn:Destroy()
	humanoid:ApplyDescription(description)
end


That worked wonders! Thanks a bunch!

1 Like

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