Why isn't this pathfinding script working?

Basically, I am trying to make a pathfind script that goes to a randomly select part of the tycoon if it is there. The first part works, it goes to a randomly selected part in the tycoon, but the next part, the despawn part of the script won’t work. Please tell me why!

Here’s my script: (PS: I know there are a lot of variable i dont use.)

local pathservice = game:GetService("PathfindingService")
local path = pathservice:CreatePath()
local db = true
local target = nil
local GetWalkingAnim = script.Parent.Animations.Attack
local WalkingAnim = script.Parent.Humanoid:LoadAnimation(GetWalkingAnim)
local TycoonName = "Tycoon1"
local db2 = true

for i,v in pairs(workspace:GetChildren()) do
	if TycoonName ~= "" then
		if #workspace:FindFirstChild(TycoonName):FindFirstChild("Builds"):GetChildren() ~= 0 and string.find(v.Name, TycoonName) then
			local FindTarget = math.random(1,#workspace:FindFirstChild(TycoonName):FindFirstChild("Builds"):GetChildren())
			target = v.Builds:GetChildren()[FindTarget]
			local random = math.random(1,5)
			if target ~= nil then
				path:ComputeAsync(script.Parent.HumanoidRootPart.Position, target.PrimaryPart.Position)
				for i, v in pairs(path:GetWaypoints()) do
					WalkingAnim:Play()
					script.Parent.Humanoid:MoveTo(v.Position + Vector3.new(10 + random/2, 0,random))
				end
			end
			script.Parent.Humanoid.MoveToFinished:Connect(function() 
				local random = math.random(5,5)
				if random == 5 then
					path:ComputeAsync(workspace:FindFirstChild(TycoonName).Essentials.Despawn.Position, script.Parent.HumanoidRootPart.Position)
					for j,k in pairs(path:GetWaypoints()) do
						WalkingAnim:Play()
						script.Parent.Humanoid:MoveTo(k.Position) -- Right here, the Humanoid isn't budging
					end
				end
			end)
		else if script.Parent ~= nil and #workspace:FindFirstChild(TycoonName):FindFirstChild("Builds"):GetChildren() == 0 then
				wait()
				script.Parent:Destroy()
			end
		end
	end
end
1 Like