How to add new enemy to table without making it restart entire script

hellooo, i’m not sure how to implement this, so when i have an enemy respawn i want it’s clone to be added to the table which is does but then it doesn’t do anything else, i originally had it restart the entire script but that caused lag every time one had to respawn, anyway heres my code.

local EnemiesFolder = workspace.Enemies
local EnemyTable = {}
local Enemies = EnemiesFolder:GetChildren()




--Services
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local CollectionService = game:GetService("CollectionService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local EXPGainedEvent = ServerStorage.Events.EXPGainedEvent
local EnemyRespawnsEvent = ReplicatedStorage.Events.EnemyRespawns


table.clear(EnemyTable)

EnemyRespawnsEvent.Event:Connect(function(Enemy)
	print(Enemy)
	table.insert(EnemyTable, Enemy)
end)

for _,v in pairs(Enemies) do

	table.insert(EnemyTable, v)
	local EnemyClone = v:Clone()

	--Calling Module
	local EnemyConfig = require(v.EnemyConfig)


	--Variables
	local Enemy = v
	local EnemyHumanoid = Enemy.Humanoid
	local EnemyHumanoidRootPart = Enemy.HumanoidRootPart
	local EnemySpawnSpot = Enemy.SpawnSpot

	local AttackCoolDown = false

	--ModuleVariables
	local Health = EnemyConfig.Health
	local WalkSpeed = EnemyConfig.WalkSpeed
	local JumpPower = EnemyConfig.JumpPower

	local Damage = EnemyConfig.Damage
	local HitCoolDown = EnemyConfig.HitCoolDown
	local FollowDistance = EnemyConfig.FollowDistance
	local RespawnTime = EnemyConfig.RespawnTime

	local Range = EnemyConfig.Range

	local Gold = EnemyConfig.Rewards.Gold
	local EXP = EnemyConfig.Rewards.EXP
	local ArmorAward = EnemyConfig.Rewards.ArmorReward
	local WeaponAward = EnemyConfig.Rewards.WeaponReward
	local ArmorChance = EnemyConfig.Rewards.ArmorChance
	local WeaponChance = EnemyConfig.Rewards.WeaponChance
	
	local EnemyName = EnemyConfig.EnemyName
	local EnemyLevel = EnemyConfig.Level
	
	--GUI
	local EnemyStats = Enemy.EnemyStats.MainFrame
	local HPTextGUI = EnemyStats.HP
	local LVGUI = EnemyStats.LV
	local NameGUI = EnemyStats.NameText
	local HealthBar = EnemyStats.HealthBar
	
	local UIBlocksFolder = ServerStorage.UIBlocks
	local ItemPopUp = UIBlocksFolder.ItemPopUp
	
	--Animations

	local Animator = Instance.new("Animator")
	Animator.Parent = EnemyHumanoid

	local AttackAnimationID = EnemyConfig.AttackAnimationID
	local AttackAnimation = Instance.new("Animation")
	AttackAnimation.Parent = Enemy.Humanoid
	AttackAnimation.Name = "AttackAnimation"
	AttackAnimation.AnimationId = AttackAnimationID
	local AttackAnimationTrack = EnemyHumanoid.Animator:LoadAnimation(AttackAnimation)

	local WalkAnimationID = EnemyConfig.WalkAnimationID
	local WalkAnimation = Instance.new("Animation")
	WalkAnimation.Parent = Enemy.Humanoid
	WalkAnimation.Name = "WalkAnimation"
	WalkAnimation.AnimationId = WalkAnimationID
	local WalkAnimationTrack = EnemyHumanoid.Animator:LoadAnimation(WalkAnimation)

	local IdleAnimationID = EnemyConfig.IdleAnimationID
	local IdleAnimation = Instance.new("Animation")
	IdleAnimation.Parent = Enemy.Humanoid
	IdleAnimation.Name = "IdleAnimation"
	IdleAnimation.AnimationId = IdleAnimationID
	local IdleAnimationTrack = EnemyHumanoid.Animator:LoadAnimation(IdleAnimation)

	--Sounds
	local AttackSoundID = EnemyConfig.AttackSoundID
	local AttackSound = Instance.new("Sound")
	AttackSound.Name = "AttackSound"
	AttackSound.Parent = Enemy
	AttackSound.SoundId = AttackSoundID
	
	local DeathSoundID = EnemyConfig.DeathSoundID
	local DeathSound = Instance.new("Sound")
	DeathSound.Name = "DeathSound"
	DeathSound.Parent = Enemy
	DeathSound.SoundId = DeathSoundID
	



	--AssigningStats 
	EnemyHumanoid.MaxHealth = Health
	EnemyHumanoid.WalkSpeed = WalkSpeed
	EnemyHumanoid.JumpPower = JumpPower
	
	NameGUI.Text = EnemyName
	LVGUI.Text = "LV" .. EnemyLevel
	HPTextGUI.Text = EnemyHumanoid.Health .. "/" .. EnemyHumanoid.MaxHealth

	EnemyHumanoidRootPart:SetNetworkOwner(nil)

	local PlayerTable = {}

	local AtSpawnPoint = false
	
	table.insert(EnemyTable, EnemyClone)
	--PlayWalkingAnimation
	local function PlayWalkAnimation()
		local Humanoid_State = EnemyHumanoid:GetState()
		if Humanoid_State == Enum.HumanoidStateType.Running then
			if WalkAnimationTrack.IsPlaying then
				return
			end
			WalkAnimationTrack:Play()
		elseif Humanoid_State == Enum.HumanoidStateType.None then
			local RunningAnimations = EnemyHumanoid:GetPlayingAnimationTracks()
			for i, Animation in pairs(RunningAnimations) do
				if Animation.IsPlaying == true then
					Animation:Stop()
				end	
			end
		end
	end
	--Moving Enemy Function
	local function MoveEnemy()
		local Target = nil
		local PlayersInGame = Players:GetPlayers()
		for _,Player in pairs(PlayersInGame) do
			local Character = Player.Character
			if Character then
				local CharacterHumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")

				if CharacterHumanoidRootPart  and (EnemyHumanoidRootPart.Position - CharacterHumanoidRootPart.Position).Magnitude < Range then
					if Target then
						if (EnemyHumanoidRootPart.Position - Target.Position).Magnitude > (EnemyHumanoidRootPart.Position - CharacterHumanoidRootPart.Position).Magnitude then
							Target = CharacterHumanoidRootPart
						end
					else
						Target = CharacterHumanoidRootPart
						PlayWalkAnimation()
						IdleAnimationTrack:Stop()

						--Put Players Into Reward Table
						if table.find(PlayerTable, Target.Parent) then
						else
							table.insert(PlayerTable, Target.Parent)
						end

					end
				end
			end
			--Stop Moving
			if  Target == nil then

				if IdleAnimationTrack.IsPlaying then
				else
					IdleAnimationTrack:Play()
					WalkAnimationTrack:Stop()
					wait(10)
					--TP Back
					if WalkAnimationTrack.IsPlaying then

					else

						if Target == nil then
							if AtSpawnPoint == true and Target == nil then
								AtSpawnPoint = false


								EnemyHumanoidRootPart.CFrame = EnemySpawnSpot.CFrame
							end
						end
					end
				end
			end
		end
		if Target then
			EnemyHumanoid:MoveTo(Target.Position)
		end

		local Humanoid_State = EnemyHumanoid:GetState()

	end
	--Attack Player

	Enemy.HitBox.Touched:Connect(function(Hit)
		if Hit.Parent:FindFirstChild("Humanoid") then
			if Hit.Parent:HasTag("Enemy") then
			else
				if AttackCoolDown == false then
					AttackCoolDown = true
					AttackSound:Play()
					AttackAnimationTrack:Play()
					Enemy.HitBox.CanTouch = false
					local Humanoid = Hit.Parent.Humanoid
					Humanoid.Health = Humanoid.Health - Damage
				end
			end
		end
		if AttackCoolDown == true then
			task.wait(HitCoolDown)
			AttackCoolDown = false
			if EnemyHumanoid.Health == 0 then
			else
				Enemy.HitBox.CanTouch = true
			end
			
		end

	end)

	Enemy.SpawnSpot.Touched:Connect(function(Hit)
		if Hit.Parent == Enemy then
			EnemyHumanoid:ChangeState(Enum.HumanoidStateType.PlatformStanding)
			WalkAnimationTrack:Stop()
			AtSpawnPoint = true
			if IdleAnimationTrack.IsPlaying then

			else
				IdleAnimationTrack:Play()
			end
		end
	end)
	local DeadCoolDown = false
	EnemyHumanoid.Died:Connect(function()
		if DeadCoolDown == false then
			DeadCoolDown = true
			DeathSound:Play()
			for i,v in pairs(PlayerTable, v) do
				local Player = Players:GetPlayerFromCharacter(v)
				local leaderstats = Player.leaderstats
				local GoldValue = leaderstats.Gold
				local EXPValue = leaderstats.EXP
				
				local ArmorAwardRange = math.random(1, 100)
				local WeaponAwardRange = math.random(1, 100)
				
				GoldValue.Value += Gold
				EXPValue.Value += EXP
				EXPGainedEvent:Fire()
				
				if ArmorAward ~= "" then
					if ArmorAwardRange <= ArmorChance then
						local Armor = game.ServerStorage.Armor:FindFirstChild(ArmorAward)
						if Armor then
							if Player.InventoryFolder.ArmorFolder:FindFirstChild(ArmorAward) then
							else
								Armor:Clone().Parent = Player.InventoryFolder.ArmorFolder
								local ItemPopUpClone = ItemPopUp:Clone()
								ItemPopUpClone.ItemDropText.Text = "You Got " .. ArmorAward
								ItemPopUpClone.ItemDropText.Position = UDim2.new(0.311, 0, 0.743, 0)
								ItemPopUpClone.Parent = Player.PlayerGui
								
							end
						end
					end
					
				end
				
				if WeaponAward ~= "" then
					if WeaponAwardRange <= WeaponChance then
						local Weapon = game.ServerStorage.Tools:FindFirstChild(WeaponAward)
						if Weapon then
							if Player.InventoryFolder.WeaponsFolder:FindFirstChild(WeaponAward) then
							else
								Weapon:Clone().Parent = Player.InventoryFolder.WeaponsFolder
								local ItemPopUpClone = ItemPopUp:Clone()
								ItemPopUpClone.ItemDropText.Text = "You Got " .. WeaponAward
								ItemPopUpClone.Parent = Player.PlayerGui
								
							end
						end
					end
				end
			end
		end
	end)
	
	--GUI
	Enemy.Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
		local Health = EnemyHumanoid.Health
		local MaxHealth = EnemyHumanoid.MaxHealth

		local HealthPercent = Health / MaxHealth

		HPTextGUI.Text = math.floor(Health) .. "/" .. MaxHealth
		HealthBar:TweenSize(UDim2.new(HealthPercent, 0, 0.4, 0))

	end)
	
	RunService.Stepped:Connect(MoveEnemy)

end

You can perhaps spawn the event connection to make it so that it doesn’t interfere?

This is because for new enemies, you aren’t setting any of the things you set for old enemies in the loop. Just make that entire enemy configuration thing a function, and call that function on each enemy added to the table so that they’re all configured correctly.

So like

local function configEnemy(v)
--all of the things you have in the for loop 
end

table.clear(EnemyTable)

EnemyRespawnsEvent.Event:Connect(function(Enemy)
	print(Enemy)
	configEnemy(Enemy)
end)

for _, v in pairs(Enemies) do
	configEnemy(v)
end

i’ve given this a shot but now it won’t find the enemyconfig script for some reason, i’ve tried various different stuff, do you have any idea why? also its only on the respawned enemies

well, after cloning the enemies, do they have the config script? It might not have been cloned correctly or something.

it does have it when cloned but for some reason the main enemy code just doesn’t detect it no matter what i do

Try printing it. It might be being added to the clone after you tried getting it in the code. If it errors while printing, try adding a “WaitForChild()”