Script won't remove values from a number value

I’m trying to make an NPC spawner that has a limit of 10 NPC’s, and I want to make it so when an NPC gets killed, It removes one number from the value and keep spawning them in until the value reaches its limit again.
This is the spawner code:

local spawners = workspace.Spawns:GetChildren()
local maxNPCs = 10
local currentNPCs = script.NPCs.Value
local spawnDummy = game.ServerScriptService.npcspawner:WaitForChild("NPC")
while task.wait(math.random(1,4)) do 
	if currentNPCs >= maxNPCs then
		return
	end
	local spawner = spawners[math.random(#spawners)]
	local dummyClone = spawnDummy:Clone()
	dummyClone:SetPrimaryPartCFrame(CFrame.new(spawner.Position + Vector3.new(0, 3, 0)))
	dummyClone.Parent = workspace
	currentNPCs = currentNPCs + 1
	end

This is the code I attempted to use to remove one from the value:

local Humanoid : Humanoid = script.Parent.Parent:FindFirstChild("Humanoid")
local NPC = script.Parent.Parent

Humanoid.Died:Connect(function()
	task.wait(3)
	game.ServerScriptService.npcspawner.NPCs.Value -= 1
	NPC:Destroy()
end)
1 Like

A different way to do this would be to put the NPCs in a folder, define a variable as “GetChildren()” of that folder, then use #[variable] or #[folder]:GetChildren() to get the folder’s total amount.

-- Define a variable with a number value
local myNumber = 42

-- Function to modify the number without removing values
local function modifyNumber(newValue)
    -- Perform some operation without removing values
    local result = newValue + 10
    return result
end

-- Call the function with your number variable
local modifiedValue = modifyNumber(myNumber)

-- Print the original and modified values
print("Original Number:", myNumber)
print("Modified Number:", modifiedValue)

This script defines a variable myNumber, then has a function modifyNumber that performs an operation (in this case, adding 10) without removing any values. The original and modified values are then printed. You can customize the modifyNumber function to perform any operation you need without losing data.

You could try GetPropertyChangedSignal

local Humanoid : Humanoid = script.Parent.Parent:FindFirstChild("Humanoid")
local NPC = script.Parent.Parent

Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
	if Humanoid.Health == 0 then
		task.wait(3)
		game.ServerScriptService.npcspawner.NPCs.Value -= 1
		NPC:Destroy()
	end
end)