So I have a very basic NPC that shoots a ball projectile but when it dies the script will still keep running and shooting the ball. So background knowledge: this ball projectile is summoned then gradually gets bigger then it shoots. So my solution is to use the humanoid.Died function to destroy the script but at the same time if the npc dies when the script is still in the middle of building the projectile, it will destroy the script or disable it thus making the unfinished projectile just stay on workspace. How would I be able to remove the projectile once the NPC dies?
Code:
Shooting the projectile
hum.Died:Connect(function()
script.Disabled = true
end)
while true do
wait()
local target = findTarget(hrp.Position)
local raycast = rayCast()
local waypoints = pathfinding:GetWaypoints()
if target then
for i, v in ipairs(waypoints) do
if pathfinding.Status == Enum.PathStatus.Success then
if(hrp.Position - target.Position).Magnitude < Settings.ShootRange.Value and (target.Position - hrp.Position):Dot(hrp.CFrame.LookVector) > 0 then
if raycast then
lookat(target, hrp)
powerball.power(hrp)
break
end
end
end
hum:MoveTo(waypoints[2].Position)
end
end
end
The Module Script
PowerBall.power = function(parenthrp)
local debris = game:GetService("Debris")
local part = Instance.new("Part")
local bv = Instance.new("BodyVelocity")
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://6769550180"
sound.Volume = .5
sound.Looped = true
bv.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
bv.P = math.huge
bv.Parent = part
part.AssemblyLinearVelocity = parenthrp.CFrame.LookVector * 50
bv.Velocity = part.AssemblyLinearVelocity
part.Material = Enum.Material.Neon
part.Anchored = true
part.Color = Color3.new(0.666667, 0.666667, 1)
part.Shape = Enum.PartType.Ball
part.CanCollide = false
part.Position = parenthrp.Position + parenthrp.CFrame.LookVector * 10
part.Size = Vector3.new(.1,.1,.1)
part.Parent = workspace
sound.Parent = part
sound:Play()
part.AssemblyLinearVelocity = parenthrp.CFrame.LookVector * 50
bv.Velocity = part.AssemblyLinearVelocity
for i, v in ipairs(lightning) do
local clone = v:Clone()
clone.Parent = part
end
for i = .1, 10, .1 do
wait()
part.Size = Vector3.new(i,i,i)
end
wait(.5)
lightsounds(part)
part.Anchored = false
part.Touched:Connect(function(hit)
local hum = hit.Parent:FindFirstChild("Humanoid")
local hrp = hit.Parent:FindFirstChild("HumanoidRootPart")
if hum and hum.Health > 0 and hrp and hit.Parent ~= parenthrp.Parent then
hum:TakeDamage(100)
end
end)
debris:AddItem(part, 10)
end
So in summary, these scripts will not run in an instant because of delays and because of that if deleted while in the middle of the script, it will stop everything entirely and just leaves what is created(the projectile) in the workspace.