I'm new to OOP, Is there a better way to make my NPCs respawn?

Hello, I am new to OOP and i’ve made an enemy system with it, but i’m just having trouble trying to find a better way to respawn NPCs without having to call a function that is the same as the function that creates the NPC. I’m just wondering if there’s a way better way to do this because i’m pretty sure this causes issues. Here is some of the code:

function createZombie()
	local newNpc = main.new(Vector3.new(math.random(-150, 400), 40, math.random(-50, 300)), zombies[math.random(1, #zombies)])
	local myRoot = newNpc.Character.HumanoidRootPart
	local myHuman = newNpc.Character.Humanoid

	myRoot:SetNetworkOwner(nil)

	myHuman:SetStateEnabled(Enum.HumanoidStateType.GettingUp, false)
	myHuman:SetStateEnabled(Enum.HumanoidStateType.Seated, false)
	myHuman:SetStateEnabled(Enum.HumanoidStateType.Swimming, false)
	myHuman:SetStateEnabled(Enum.HumanoidStateType.Ragdoll, false)
	myHuman:SetStateEnabled(Enum.HumanoidStateType.Physics, false)
	myHuman:SetStateEnabled(Enum.HumanoidStateType.Climbing, false)

	local runAnim = Instance.new("Animation")
	runAnim.AnimationId = "rbxassetid://15515631348"
	runAnim.Parent = newNpc.Character.Humanoid.Animator

	newNpc.Character.Humanoid.Animator:LoadAnimation(runAnim):Play()

	myHuman.Died:Once(function()
		local dataManager = require(game.ReplicatedStorage.DataManager)

		local tag = myHuman:FindFirstChild("creator")
		if tag then
			local player = tag.Value

			if player then
				local data = dataManager:Get(player)
				
				if data then
					data.kills += 1
					data.money = data.money + 15

					player.leaderstats.Kills.Value = data.kills
					player.leaderstats.Money.Value = data.money

					--[[else
						warn(player.Name, "does not have profile loaded")--]]
				end
			end
		end
		task.wait(5)
		newNpc.Character:Destroy()
		createZombie()
		setmetatable(newNpc, nil)
	end)

	while task.wait(0.5) do
		if newNpc:IsAlive(myHuman) and newNpc.Character then
			local target = main:findTarget(myRoot, myHuman)
			if target then
				main:findPath(target, myRoot, myHuman)
			else
				main:walkRandomly(myRoot, myHuman)
			end
		end
	end	
end
2 Likes

I don’t really see any drawbacks to simply creating a new NPC when one dies. If you’re facing issues with that, then what are those issues?

1 Like

I suggest to put the instantiated NPC on an array and outside the function would have a RunService.Heartbeat() and iterate over the array and do the necessary stuff in there.

1 Like