--Over complicated function for instantly switching targets upon kill

local targetDeathConnection = nil
local trackedTarget = nil
function trackDeath(newTarget)
	
	if trackedTarget ~= newTarget then
		
		if targetDeathConnection then
			targetDeathConnection:Disconnect()
			targetDeathConnection = nil
		end
		
		trackedTarget = newTarget
		
		targetDeathConnection = newTarget.Parent.Humanoid.Died:Connect(function()

			
			targetDeathConnection:Disconnect()
			targetDeathConnection = nil
			
			if combat.getMunition(munition) then
				target = core.findTarget()
				if target then
					trackDeath(target)
				end
			end
		end)
	end
end

core.spawn(function()
	while myHuman.Health > 0 do
		
		
		if combat.getMunition(munition) then
			if target then
				
				--If we have a target unless we haven't attacked in 5 seconds don't switch
				if tick() - lastAttack > 5  then
					target = core.findTarget()
				end
			else
				target = core.findTarget()
			end
			
			if target then
				--Instant target switching
				trackDeath(target)
			end
		else
			--Sets target to nil when no ammo to return home and restock
			target = nil
		end
		
		wait(1)
	end
end)

myHuman.Died:Connect(function()
	crash()
	
	if targetDeathConnection then
		targetDeathConnection:Disconnect()
		targetDeathConnection = nil
	end
	
	wait(mySettings.Respawn.Time.Value)
	if mySettings.Respawn.Value then
		clone.Parent = script.Parent.Parent
	end
	script.Parent:Destroy()
end)





















