My aim is to make the NPC move to a random location every 1 to 7 seconds. My issue is that the code is being repeatedly executed. I’m assuming that I could utilise a debounce but I might be wrong.
Here is the code:
while CustomWait(math.random(1,7)) do
print("While loop started")
if moveRandomly == true then
local newLocation
do repeat
newLocation = randomLocations:FindFirstChild(math.random(1, 10))
CustomWait()
until
newLocation ~= randomLocation
end
path:ComputeAsync(humRootPart.Position, newLocation.Position)
local wayPoints = path:GetWaypoints()
for i, wayPoint in pairs(wayPoints) do
humanoid:MoveTo(wayPoint.Position)
humanoid.MoveToFinished:Wait()
end
humanoid:MoveTo(newLocation.position)
humanoid.MoveToFinished:Wait()
print("While loop started")
if moveRandomly == true then
local newLocation
do repeat
newLocation = randomLocations:FindFirstChild(math.random(1, 10))
CustomWait()
until
newLocation ~= randomLocation
end
path:ComputeAsync(humRootPart.Position, newLocation.Position)
local wayPoints = path:GetWaypoints()
for i, wayPoint in pairs(wayPoints) do
humanoid:MoveTo(wayPoint.Position)
humanoid.MoveToFinished:Wait()
end
humanoid:MoveTo(newLocation.position)
humanoid.MoveToFinished:Wait()
Do you think that I could remove the while wait loop and just have and if statement that keeps running. I could then do:
local debounce = false
if moveRandomly == true and debounce == false then
debounce = true
local newLocation
do repeat
newLocation = randomLocations:FindFirstChild(math.random(1, 10))
task.wait()
until
newLocation ~= randomLocation
end
path:ComputeAsync(humRootPart.Position, newLocation.Position)
local wayPoints = path:GetWaypoints()
for i, wayPoint in pairs(wayPoints) do
humanoid:MoveTo(wayPoint.Position)
humanoid.MoveToFinished:Wait()
end
humanoid:MoveTo(newLocation.position)
humanoid.MoveToFinished:Wait()
elseif moveRandomly == false and debounce == false then
debounce = false
Depends what you’re trying to do. If you’d want a constant delayed iteration, I’d recommend using the while loop otherwise the if statement should work too, if persistently called as a function.