Hi,
Im making script that should delete all npc’s from folder if there too many of them, and add if there only few or none. Also this script should delete all npc if player entered new zone and add new npcs.
But this script do not work. I noticed that this script adds npc’s only if i equip or unequip tool in my inventory, but its doesnt delete them for example i equipped and unequipped my tool like 20 times and there like 40 npcs and script do not clear them. What wrong with this script? What should i change? Or maybe you know better way to make something like this?
heres script:
local folderchilds = workspace.NPCs:GetChildren()
local number = #folderchilds
while true do
HumanoidRootPart.Touched:Connect(function(hit)
if hit.Name == "Zone 1" then
if number ~= 3 then
print("Added NPCs")
game.ReplicatedStorage.Citizen:Clone().Parent = workspace.NPCs
end
end
if hit.Name == "Zone 2" then
workspace.NPCs:ClearAllChildren()
print("Added NPCs")
game.ReplicatedStorage.Monster:Clone().Parent = workspace.NPCs
end
end)
if number >= 3 then
break
end
if number >= 3 then
workspace.NPCs:ClearAllChildren()
end
wait(5)
end
You are setting the variable ‘folderchilds’ to children of an folder. If there’s 3 children at the time when you are setting this variable, then the variable would look like that: {npc1, npc2, npc3}, even when u add an npc to a folder, the ‘folderchilds’ variable will stay the same because it’s an variable and it stores children that the NPCs folder had when u first set the ‘folderchilds’ variable
local folder = workspace.NPCs
while true do
HumanoidRootPart.Touched:Connect(function(hit)
if hit.Name == "Zone 1" then
if #folder:GetChildren() ~= 3 then
print("Added NPCs")
game.ReplicatedStorage.Citizen:Clone().Parent = workspace.NPCs
end
end
if hit.Name == "Zone 2" then
workspace.NPCs:ClearAllChildren()
print("Added NPCs")
game.ReplicatedStorage.Monster:Clone().Parent = workspace.NPCs
end
end)
if #folder:GetChildren() >= 3 then
break
end
if #folder:GetChildren() >= 3 then
workspace.NPCs:ClearAllChildren()
end
wait(5)
end