Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

AI from Server Storage not working?

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

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.

2 comments

0

That is what line 12 is for.

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.