MoveTo(), kill player within 10 magnitude of the NPC

v.NPC.Humanoid:MoveTo(v.Start.Position)
while not v.NPC.Humanoid.MoveToFinished:wait() do
    if spotted == true and (workspace:WaitForChild("Bylocks").HumanoidRootPart.Position - 
        v.NPC.HumanoidRootPart.Position).magnitude <= 10 then
        workspace:WaitForChild("Bylocks"):WaitForChild("UpperTorso"):Destroy()
    end
end

The intent of this is when it begins moving while it hasn’t finished moving that if you are within 10 maginitude or studs or whatever that it would kill me. However this isn’t the case, it doesn’t kill me. Though it still finishes because when I put a print after the while loop it prints.

Any fixes you have in mind?

A post was merged into an existing topic: Off-topic and bump posts

The problem here is the condition in the while loop. Wait() will halt the current thread of execution until the event has fired and return the results of the event fired.

In this case, the code will call MoveToFinished:Wait() and wait until the humanoid has reached its target. Then, it returns a bool representing whether or not the target timed out which would be true. This means the condition in your loop evaluates to something along the lines of not true which in turn evaluates to false, so the loop is skipped.

The solution is to connect a listener to the event instead that sets a boolean to false when called. This boolean should act as the conditional for the loop instead.

v.NPC.Humanoid:MoveTo(v.Start.Position)
local targetReached = false
v.NPC.Humanoid.MoveToFinished:Connect(function(successful)
    targetReached = true
end)
while not targetReached do
    if spotted == true and (workspace:WaitForChild("Bylocks").HumanoidRootPart.Position - 
        v.NPC.HumanoidRootPart.Position).magnitude <= 10 then
        workspace:WaitForChild("Bylocks"):WaitForChild("UpperTorso"):Destroy()
    end
    wait()
end
4 Likes