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

NPC doesn't shoot oil cups, however, still retains Its pathfinding (?)

Hello!

As the title says, an NPC doesn't shoot oil cups, but still retains Its pathfinding, I used coroutine for the shooting script

Script:

local NPC = script.Parent
local Pathfinding = game:GetService("PathfindingService")
local TweenService = game:GetService("TweenService")
local player

game.Players.PlayerAdded:Connect(function(client)
	player = client
end)

repeat wait() until player ~= nil

while wait() do
	local path = Pathfinding:CreatePath()
	
	path:ComputeAsync(NPC.Torso.Position, player.Character.PrimaryPart.Position)
	
	if path.Status == Enum.PathStatus.Success then
		
		local Positions = path:GetWaypoints()
		
		for i,v in pairs(Positions) do
			
			local position = Instance.new("Part")
			
			position.Parent = game.Workspace
			
			position.Size = Vector3.new(1,1,1)
			
			position.Position = v.Position
			
			position.Transparency = 1
			
			NPC.Humanoid:MoveTo(position.Position)
			
			NPC.Humanoid.MoveToFinished:Wait(2)
			
			position:Destroy()
			
		end
		
	end
end

coroutine.wrap(function()
	while wait(0.3) do
		NPC.Pew:Play()
		local OilCup = game:GetService("ReplicatedStorage").Stuff.Oil:Clone()
		game:GetService("Debris"):AddItem(OilCup,3)
		OilCup.Parent = game.Workspace
		OilCup.Position = NPC.Gun.Position
		OilCup.Orientation = NPC.Gun.Orientation
		OilCup.CanCollide = false
		local TweenProperties = {
			CFrame = OilCup.CFrame + (OilCup.CFrame.LookVector*50)
		}
		local InfoThing = TweenInfo.new(
			2,
			Enum.EasingStyle.Back,
			Enum.EasingDirection.Out,
			0,
			false,
			0
		)
		local PartTween = TweenService:Create(OilCup, InfoThing, TweenProperties)
		PartTween:Play()
	end
end)

1 answer

Scripts run top to bottom. You are making the script wait in the Pathfinding and therefore yield everything. Once the NPC has reached its destination, the script can continue further and then wraps your coroutine. So put the coroutine infront of you Pathfinding and call it within pathfinding or before.

Also you need to call the function so that coroutine.wrap actually starts.

Example:

local cr = coroutine.wrap(function() --Assign the coroutine function to a variable
	--Code
end)

--The coroutine does not run. We need to call the function
cr() --calling the function

Some other tips:

Try not to do while wait() true without a break because that function runs indefinitely.

Try to put everything Async into PCalls (or coroutines) as they are more likely to error.

1 comment

0

Alright!

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