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

AI from Server Storage not working?

Asked by 2 years ago

So I am working on a game and I added simple follow AI so an NPC follows the nearest player. The ai Spawns randomly in in randomly generated rooms when the AI does spawn they don't move.

Here is the code

local humanoid = script.Parent.Humanoid
local HRP = script.Parent.HumanoidRootPart

local pathfindingservice = game:GetService("PathfindingService")

local Players = game:GetService("Players")

local maxDistance = 40

local destination = nil

repeat wait() until script.Parent == workspace

while true do
    wait(0.016)
    local nearestPlayer, nearestDistance
    for _, player in pairs(Players:GetPlayers()) do
        local character = player.Character
        local distance = player:DistanceFromCharacter(HRP.Position)
        if not character or 
            distance > maxDistance or
            (nearestDistance and distance >= nearestDistance)
        then
            continue
        end
        nearestDistance = distance
        nearestPlayer = player
    end
    print("The nearest player is ", nearestPlayer)
    if nearestPlayer ~= nil then
        humanoid:MoveTo(nearestPlayer.Character.HumanoidRootPart.Position)
    end
end

I don't know why it is not working.

1 answer

Log in to vote
0
Answered by
epoke466 100
2 years ago

You need to disable the script until the NPC is in workspace, this is because the NPC cannot have a position in Server Storage. (Line 19) The script cannot find the player nearest to the NPC without the position of the NPC.

0
That is what line 12 is for. Pinksheep2007 5 — 2y
0
If the ai is going into workspace but then not working I am not sure what is wrong, I have been having problems w/ pathfinding too, it could be a bug. epoke466 100 — 2y
Ad

Answer this question