Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

AI script doesn't work??

Asked by
lucas4114 607 Moderation Voter
8 years ago

It worked perfectly like this:

while wait() do
    local distances = {}
    local charwithdistance = {}
    for number,char in pairs (game.Workspace.NPCs:GetChildren()) do
        local distance = (char.Head.Position - script.Parent.Head.Position).magnitude
        distances[number] = distance
        charwithdistance[distance] = char
    end
    table.sort(distances)
    for number2, plr in pairs (distances) do
        local closestdistance = distances[(number2 + 1)]
        local closestplayer = charwithdistance[(closestdistance)]
        script.Parent.Humanoid:MoveTo(closestplayer.Head.Position)
    end
end

But I also didn't want it to kill AIs on its team so then I did this:

while wait() do
    local distances = {}
    local charwithdistance = {}
    for number,char in pairs (game.Workspace.NPCs:GetChildren()) do
        local distance = (char.Head.Position - script.Parent.Head.Position).magnitude
        distances[number] = distance
        charwithdistance[distance] = char
    end
    table.sort(distances)
    for number2, plr in pairs (distances) do
        local closestdistance = plr
        local closestplayer = charwithdistance[(closestdistance)]
        if not closestplayer.Owner.Value == script.Parent.Owner.Value then
            script.Parent.Humanoid:MoveTo(closestplayer.Head.Position)
            return
        end
    end
end

But now it doesn't work and the AI doesn't do anything, idk how to fix this, and the output says: 07:41:40.962 - Workspace.NPCs.AI.Ai Script:14: attempt to index local 'closestplayer' (a nil value) 07:41:40.963 - Stack Begin 07:41:40.964 - Script 'Workspace.NPCs.AI.Ai Script', Line 14 07:41:40.965 - Stack End

0
Remove the "local" before "closestplayer". That local means It'll only work in that loop/function/if statement. I don't know if this is your problem, but it might help lightpower26 399 — 8y
0
No I found out now, I needed to use break instead of return ty for trying anyways ;p lucas4114 607 — 8y

Answer this question