The enemies in my game stop chasing and attacking me after I respawn. I can’t find the issue anywhere.
local players = game:GetService("Players")
local enemiesFolder = game.Workspace:WaitForChild("Enemies")
local chaseRange = 20
-- Function to make an enemy chase a specific player
local function makeEnemyChasePlayer(enemy, player)
local humanoid = enemy:FindFirstChildOfClass("Humanoid")
local rootPart = enemy:FindFirstChild("HumanoidRootPart")
if not humanoid or not rootPart then
warn("Enemy is missing essential parts:", enemy.Name)
return
end
-- Chase coroutine
coroutine.wrap(function()
while player.Character and player.Character:FindFirstChild("HumanoidRootPart") and player.Character.Humanoid.Health > 0 do
local playerRootPart = player.Character.HumanoidRootPart
local distance = (rootPart.Position - playerRootPart.Position).Magnitude
if distance <= chaseRange then
humanoid:MoveTo(playerRootPart.Position) -- Move enemy toward player
wait(0.1)
else
break -- Stop chasing if the player moves out of range
end
end
end)()
end
-- Function to handle player respawn
local function handlePlayerRespawn(player)
player.CharacterAdded:Connect(function(character)
wait(0.5) -- Ensure the character is fully initialized
-- Assign enemies to resume chasing this player if nearby
for _, enemy in pairs(enemiesFolder:GetChildren()) do
if enemy:IsA("Model") and enemy:FindFirstChildOfClass("Humanoid") and enemy:FindFirstChild("HumanoidRootPart") then
local rootPart = enemy:FindFirstChild("HumanoidRootPart")
local playerRootPart = character:FindFirstChild("HumanoidRootPart")
if rootPart and playerRootPart then
local distance = (rootPart.Position - playerRootPart.Position).Magnitude
if distance <= chaseRange then
makeEnemyChasePlayer(enemy, player)
end
end
end
end
end)
end
-- Connect respawn handling for existing players
for _, player in pairs(players:GetPlayers()) do
handlePlayerRespawn(player)
end
-- Connect respawn handling for new players
players.PlayerAdded:Connect(function(player)
handlePlayerRespawn(player)
end)
Any help is appreciated