Update for i, v in folder:GetChildren() Loop

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    If zombie is added, update the list with it and run code for the zombies.

  2. What is the issue? Include screenshots / videos if possible!
    when i try to run this function when childadded:

local function GetZombies()
	for _, v in workspace.Zombies:GetChildren() do
		local Enabled
		local Leaderstat_Reward_Value = rewards[v.Name][1]
		local Humanoid = v.Humanoid
		Humanoid.Died:Connect(function()
			local tag = Humanoid:FindFirstChild("creator")
			if tag ~= nil then
				local leaderstats = tag.Value:FindFirstChild("leaderstats")
				if leaderstats == nil then warn("Leaderstats are nil. noot giving the reward.") else
					leaderstats.Exp.Value = leaderstats.Exp.Value + Leaderstat_Reward_Value
				end
				if rewards[v.Name][2] == true then
					local box = game:GetService("ServerStorage").AmmoBox:Clone()
					box.Parent = workspace.Ammo
					box:MoveTo(v.Torso.Position)
				end
				--local evente = game:GetService("ReplicatedStorage").Events.SoundKill:FireClient(tag.Value)
				local evente2 = game:GetService("ReplicatedStorage").Events.ZombieKilled:FireClient(tag.Value,rewards[v.Name],Leaderstat_Reward_Value,v.Name)
			end
		end)
	end
end

it duplicated the code for the zombies, so it would spawn 2 ammoboxes for example when one zombie dies.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    As I said, tried to run it as a function when child is added, but it gives me no proper result.
2 Likes

That’s because you’re running the for loop every time the function is called. You need to do something like this instead:

local function GetZombies(v)
	local Enabled
		local Leaderstat_Reward_Value = rewards[v.Name][1]
		local Humanoid = v.Humanoid
		Humanoid.Died:Connect(function()
			local tag = Humanoid:FindFirstChild("creator")
			if tag ~= nil then
				local leaderstats = tag.Value:FindFirstChild("leaderstats")
				if leaderstats == nil then warn("Leaderstats are nil. noot giving the reward.") else
					leaderstats.Exp.Value = leaderstats.Exp.Value + Leaderstat_Reward_Value
				end
				if rewards[v.Name][2] == true then
					local box = game:GetService("ServerStorage").AmmoBox:Clone()
					box.Parent = workspace.Ammo
					box:MoveTo(v.Torso.Position)
				end
				--local evente = game:GetService("ReplicatedStorage").Events.SoundKill:FireClient(tag.Value)
				local evente2 = game:GetService("ReplicatedStorage").Events.ZombieKilled:FireClient(tag.Value,rewards[v.Name],Leaderstat_Reward_Value,v.Name)
			end
		end)
end

for _, in workspace.Zombies:GetChildren() do GetZombies(v) end

workspace.Zombies.ChildAdded:Connect(GetZombies)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.