I would like to make it so when the hunger value < 40, an event is fired when the NPC has finished moving. My problem is that when the “if moveRandomly == true and db == false then” statement is run, if I put the food into the food bowl (which sets the foodInBowl value to true) whilst the “CustomWait(math.random(3, 7))” line is running, the NPC now has two places to go to as it will want to go to the food bowl to eat food but also go to the randomly selected location. Here is my code:
local pathFindingService = game:GetService("PathfindingService")
local CustomWait = require(game:GetService("ReplicatedStorage").CustomWait)
local NPC = workspace:WaitForChild("Gary")
local humRootPart = NPC:WaitForChild("HumanoidRootPart")
local humanoid = NPC:WaitForChild("Humanoid")
humRootPart:SetNetworkOwner(nil)
local rs = game:GetService("ReplicatedStorage")
local locations = script.Parent
local randomLocations = locations:WaitForChild("RandomLocations")
local lowHunger = rs:WaitForChild("Events").LowHunger
local foodBowl = locations:WaitForChild("FoodBowl")
local litterBox = script.Parent.LitterBox
local foodInBowl = foodBowl.FoodInBowl
local path = pathFindingService:CreatePath()
local moveRandomly = true
local debounce = false
local stop = false
local db = false
local randomLocation = randomLocations:FindFirstChild(math.random(1, 10))
path:ComputeAsync(humRootPart.Position, randomLocation.Position)
local wayPoints = path:GetWaypoints()
for i, wayPoint in pairs(wayPoints) do
humanoid:MoveTo(wayPoint.Position)
humanoid.MoveToFinished:Wait(1)
end
humanoid:MoveTo(randomLocation.Position)
local hunger
humanoid.MoveToFinished:Connect(function(randomLocation)
lowHunger.Event:Connect(function(plr)
hunger = plr:WaitForChild("Stats").Hunger
if foodInBowl.Value == true then
moveRandomly = false
path:ComputeAsync(humRootPart.Position, foodBowl.Position)
local wayPoints = path:GetWaypoints()
for i, wayPoint in pairs(wayPoints) do
humanoid:MoveTo(wayPoint.Position)
humanoid.MoveToFinished:Wait(1)
end
humanoid:MoveTo(foodBowl.Position)
humanoid.MoveToFinished:Wait()
end
end)
if moveRandomly == true and db == false then
db = true
CustomWait(math.random(3,7))
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(1)
end
humanoid:MoveTo(newLocation.position)
humanoid.MoveToFinished:Wait()
db = false
elseif moveRandomly == false and db == false then
db = true
workspace.Sounds.Eat:Play()
CustomWait(1)
hunger.Value = 100
foodBowl.Food.Transparency = 1
foodInBowl.Value = false
moveRandomly = true
db = false
end
end)