I created a script where any models tagged with "Monsters" using the collection service will follow the player if in the desired distance. My problem is that when I test it, the monster always prioritizes the oldest player over the new one. For example, the monster is following player 2 but then when in the range of player 1, it immediately switches target and heads towards player 1. I thought of using deBounce but it's not helping. Any suggestions or ideas that can help me? Please and thank you.
local chasing = false
-----------FUNCTIONS
local runService = game:GetService("RunService")
runService.Stepped:Connect(function()
local players = game.Players:GetPlayers()
for i = 1, #players do
repeat wait() until players[i].Character ~= nil
local humroot = players[i].Character.HumanoidRootPart
local monsters = collectionService:GetTagged("Monster")
for i = 1, #monsters do
local root = monsters[i].PrimaryPart
local distance = (humroot.Position - root.Position).Magnitude
if distance < 20 and not chasing then
chasing = true
local cFrameX = humroot.CFrame.X
local cFrameZ = humroot.CFrame.Z
local goal = {}
goal.CFrame = CFrame.new(cFrameX, root.CFrame.Y, cFrameZ)
root.CFrame = CFrame.new(root.Position, humroot.Position)
local tweenService = game:GetService("TweenService")
local tween = tweenService:Create(root, TweenInfo.new(distance * .2), goal)
tween:Play()
else
chasing = false
end
end
end
end)
