Trying to move all Fishes at the same time but only 1 moves

hello, I’m trying to make an aquarium where all the fishes swim to a random location at random times, however, when I run my script only 1 fish is moving around, if you have any idea how to make all of them move at the same time while also keeping all of the moving random for each fish, please help.

local border = workspace.Aquarium.TheBordersPart
local xStart = border.Position.X - (border.Size.X / 2)
local xEnd = border.Position.X + (border.Size.X / 2)
local yStart = border.Position.Y - (border.Size.Y / 2)
local yEnd = border.Position.Y + (border.Size.Y / 2)
local zStart = border.Position.Z - (border.Size.Z / 2)
local zEnd = border.Position.Z +(border.Size.Z / 2)

local tweenService = game:GetService("TweenService")

for i,Fish in pairs(workspace.Aquarium.Fishes:GetChildren()) do
	while true do
		local position = Vector3.new(math.random(xStart,xEnd),math.random(yStart,yEnd),math.random(zStart,zEnd))
		local SwimTime = math.random(2,5)
		
		Fish.CFrame = CFrame.lookAt(Fish.Position,position)
		
		tweenService:Create(Fish,
			TweenInfo.new(SwimTime),
			{Position = position}
		):Play()
		
		wait(math.random(0,1))
		wait(SwimTime)
	end
end

For loops are designed that way that when the code inside of them is finished, only then it skips to the next index, which means that if there is a while loop inside, then it will be ran only once, to overcome the problem you should open a new thread for each while loop, u can look into documentation of coroutine.wrap()

2 Likes

What I am saying is this:

for i,Fish in pairs(workspace.Aquarium.Fishes:GetChildren()) do
coroutine.wrap(function()
	while true do
		local position = Vector3.new(math.random(xStart,xEnd),math.random(yStart,yEnd),math.random(zStart,zEnd))
		local SwimTime = math.random(2,5)
		
		Fish.CFrame = CFrame.lookAt(Fish.Position,position)
		
		tweenService:Create(Fish,
			TweenInfo.new(SwimTime),
			{Position = position}
		):Play()
		
		wait(math.random(0,1))
		wait(SwimTime)
	end
end)()
end

Sorry for weird formation, I am on phone

2 Likes

Thanks a lot and its ok the formation is perfect, as long as it works i love it