Help with Custom Ai Path

Hello, i have a AI and the paths are completely random, script looks like this

local Rand = Random.new()
local function Patrol()
	if IsPatrolling then
		local r = Rand:NextInteger(1, #Waypoints)
		local Waypoint = Waypoints[r]

		if not HasTarget then
			MoveTo(Waypoint)
		else
			task.wait()
		end

		-- No need for infinite loops
		Patrol()
	end
end

i tried doing this to give it custom path

local Rand = Random.new()
local function Patrol()
	if IsPatrolling then
		local Start = MoveTo(workspace.waypoints.W1)
		local Middle = MoveTo(workspace.waypoints.W2)
		local End = MoveTo(workspace.waypoints.W3)
		local r = Rand:NextInteger(Start, Middle, End)
		local Waypoint = Waypoints[r]

		if not HasTarget then
			MoveTo(Waypoint)
		else
			task.wait()
		end


		Patrol()
	end
end

it kinda works, it goes to the correct path in order but does not loop anyhelp?

1 Like

Remove a Patrol function in a Patrol function

local function Patrol()
	if IsPatrolling then
		local Start = MoveTo(workspace.waypoints.W1)
		local Middle = MoveTo(workspace.waypoints.W2)
		local End = MoveTo(workspace.waypoints.W3)
		local r = Rand:NextInteger(Start, Middle, End)
		local Waypoint = Waypoints[r]

		if not HasTarget then
			MoveTo(Waypoint)
		else
			task.wait()
		end


		Patrol() --this one since it loop call 
	end
end
1 Like
local function Patrol()
	if IsPatrolling then
		local Start = MoveTo(workspace.waypoints.W1)
		local Middle = MoveTo(workspace.waypoints.W2)
		local End = MoveTo(workspace.waypoints.W3)
		local r = Rand:NextInteger(Start, Middle, End)
		local Waypoint = Waypoints[r]
		if not HasTarget then
			MoveTo(Waypoint)
		else
			task.wait()
		end
		Patrol()
	end
end

You’re attempting to call the function before it has even been defined (unless you were intending to achieve recursion but even then you’d still need to call the function at least once from outside the function for it to be executed initially).

1 Like

so what should i do to fix it?

local function Patrol()
	if IsPatrolling then
		
		local Folder = game.Workspace.waypoints
		local Start = Folder.W1
		local Middle = Folder.W2
		local End = Folder.W3
		
		local r = Rand:NextInteger(3, #Start, #Middle, #End)
		local Waypoint = Waypoints[r]
		if not HasTarget then
			MoveTo(Waypoint)
		else
			task.wait()
		end
		Patrol()
	end
end

i tried that but also dident work

I didn’t call the function if you need to call the function then you need to do so outside of the definition of the function itself, like this.

function hw()
	print("Hello world!")
end

hw()

I believe this is what you need.

local function Patrol()
	if IsPatrolling then

		local Folder = game.Workspace.waypoints
		local Start = Folder.W1
		local Middle = Folder.W2
		local End = Folder.W3

		local r = Rand:NextInteger(3, #Start, #Middle, #End)
		local Waypoint = Waypoints[r]
		if not HasTarget then
			MoveTo(Waypoint)
		else
			task.wait()
		end
	end
end

Patrol()