Search code examples
luarobloxluau

Dummy doens't follow the Character of the Player


I have been made a code but he doens't work. The code basically makes a Humanoid of the dummy follow a player, but the humanoid doens't follow the Character. Here is the code.,

function followplayer()
local closestplayer, closestdistance = nil, 200
local dummy = workspace.Follow.Dummy
for i, player in pairs(workspace:GetChildren()) do
    if player:FindFirstChild("Humanoid") ~= dummy then
        closestdistance = (player.Character.HumanoidRootPart.Position - dummy.PrimaryPart.Position).Magnitude
        closestplayer = player.Character.HumanoidRootPart
    end
end

end

while true do
wait(.2)
local humanoid = workspace.Follow.Dummy.Humanoid
local Player = game.Players.PlayerAdded:Connect(function(plr)
    local player = plr.Character:WaitForChild("HumanoidRootPart")
    humanoid:MoveTo(player.Position)
    wait(1)
    followplayer()
end)

end


Solution

  • First of all, your followplayer function does nothing. I see that it attempts to calculate some values that it won't even return, but even that fails since the upper if statement's condition will never be true (you're not getting players correctly, and you shouldn't check for them being the dummy, which will never be the case). Basically, that function computes values that it does nothing with, so it's useless.

    The while true loop is placed incorrectly. You just Connect once, and they wait for the result, without stopping. If you use an infinite loop, you will Connect multiple times, which is unnecessary and will hurt performance. You probably want to put it in the connected function.

    In the end, your code should look like this:

    local plrs = game:GetService("Players")
    local humanoid = workspace.Follow.Dummy.Humanoid
    plrs.PlayerAdded:Connect(function(plr)
        local character = plr.Character or plr.CharacterAdded:Wait()
        local player = character:WaitForChild("HumanoidRootPart")
        while true do
            humanoid:MoveTo(player.Position)
            task.wait(1)
        end
    end)
    

    I haven't checked it but this should work. I made a few minor changes as well:

    • changed wait with task.wait which is simply better.
    • replaced the character detection with a waiting expression
    • discarded the returned Connection because you don't use it
    • replaced game.Players with a variable that used GetService to get the Players service