Search code examples
luaroblox

Pairs loop not running roblox


So, I was trying to make a monster in roblox. However there was something wrong but then I did some debugging and realized that the pairs I did to loop every single player in my script was not running. Here's my code:

local dummy = script.Parent
local hrp = dummy.PrimaryPart
local sight = 30
local run = game:GetService("RunService")
local playerss = game:GetService("Players")
local players = playerss:GetChildren()
print("run")

run.Heartbeat:Connect(function()
    print("in loop")
        for _,player in pairs(players) do
        local phrp = player.PrimaryPart
        local dist = (hrp.Position - phrp.Position).Magnitude
        print("on it")
        if dist < sight then
            print(phrp.Postion)
            dummy.Humanoid.WalkToPoint = phrp.Position
            dummy.Humanoid:MoveTo(phrp.Position)
        end
    end
end)

I tried looking for forums but NOTHING worked.


Solution

  • You have a timing issue. The Script first runs when the monster is first loaded into the Workspace. So, it grabs all the services, it grabs the list of the current players, it connects to the heartbeat signal.

    The thing is, you never fetch an updated list of players. So it is looping over the list of players that were present when the Script first ran. And it's highly likely that the number of players that were present was zero.

    So to fix your issue, move the line local players = playerss:GetChildren() inside the heartbeat connection.