Whats wrong with my script?

So I’m trying to make it so that everyone near me will teleport somewhere then teleport back to their previous position after a couple of seconds all at the same time. The problem is that it’s teleporting everyone 1 by 1 instead of all at the same time?

remote.OnServerEvent:Connect(function(Iskandar)
	for _, plr in pairs(game.Players:GetChildren()) do 
		local prevposition = plr.Character.HumanoidRootPart.CFrame
		local xOffset = math.random(-50,50)
		local zOffset = math.random(-50,50)
		if (plr.Character.HumanoidRootPart.Position - Iskandar.Character.HumanoidRootPart.Position).Magnitude <= 100 then
			plr.Character.HumanoidRootPart.CFrame = CFrame.new(1549.508 + xOffset, 4210.445, 3454.124 + zOffset)		
		end	
		wait(1)
		plr.Character.HumanoidRootPart.CFrame = prevposition
	end
end)

Someone also told me to not use a for loop but he also said that he doesn’t know what to use. Im also pretty new so I don’t know what to use either. Do you guys know how I can fix this?

1 Like

Probably because you have a wait(1) in which is slowing it down, you should try using task.spawn and putting everything inside your for loop in it

remote.OnServerEvent:Connect(function(Iskandar)
	for _, plr in pairs(game.Players:GetChildren()) do 
		task.spawn(function()
           local prevposition = plr.Character.HumanoidRootPart.CFrame
		   local xOffset = math.random(-50,50)
		   local zOffset = math.random(-50,50)
		   if (plr.Character.HumanoidRootPart.Position - Iskandar.Character.HumanoidRootPart.Position).Magnitude <= 100 then
			   plr.Character.HumanoidRootPart.CFrame = CFrame.new(1549.508 + xOffset, 4210.445, 3454.124 + zOffset)		
		   end	
		   task.wait(1)
		   plr.Character.HumanoidRootPart.CFrame = prevposition
        end)
	end
end)

Or use coroutine since its better than spawn.

You can also pause a coroutine (not sure if you can do it with spawn)

1 Like

And use Players:GetPlayers() instead of Players:GetChildren() since its recommended to do so.

2 Likes

The problem was already solved by @TenBlocke

1 Like

Thanks so much! It’s working now. Btw, can you explain how task works? Sorry, I’m pretty new and I haven’t really used task before.

task is a library, but more specifically task.spawn creates a seperate thread for the function in it’s parameters to run in without yielding, more details on the task library are here. Coroutines are a viable option because it provides more control over your threads but i used task.spawn here instead because it seemed like a simple task

2 Likes