How do I update the parts in the model?

I have a model. Another models are added to this model after some time. But when I use loop, it sees 0 items. How do I fix this? I know about the ChildAdded function, but I can’t figure out where to put it

The added parts are visible in this model in workspace for me etc. But the SCRIPT doesn’t see them

this script does not output " print(1), it thinks that there are 0 details"

for _, v in pairs(game.Workspace.Bottles:GetDescendants()) do
	print(1)
	if v:IsA("BasePart") then
		v.Touched:Connect(function(Hit)
			print(2)
			local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
			if Player and Player ~= nil then
				Player.leaderstats.Money.Value = Player.leaderstats.Money.Value + v.Parent:FindFirstChildWhichIsA('IntValue').Value
				v.Parent:Destroy()
			end
		end)
	end
end

Screenshot_6

1 Like

the script should be able to see it, it probably just didnt load in. In that case just use ChildAdded or WaitForChild if you have a specific part that needs to be loaded in

Instance | Roblox Creator Documentation works like this:

Bottles.ChildAdded:Connect(function(child)
  -- the rest of your script
end)

For loops only run once if they’re only called once, meaning you need an event to trigger them.

Okay, but when I write the childadded function, my script stops functioning, because the Touched function is embedded there, and it will only work when a new part is added to the model

i made that:

BottlesFolder.ChildAdded:Connect(function()
for _, v in pairs(game.Workspace:WaitForChild("Bottles", true):GetDescendants()) do
	print(1)
	if v:IsA("BasePart") then
		v.Touched:Connect(function(Hit)
			print(2)
			local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
			if Player and Player ~= nil then
				Player.leaderstats.Money.Value = Player.leaderstats.Money.Value + v.Parent:FindFirstChildWhichIsA('IntValue').Value
				v.Parent:Destroy()
			end
		end)
	end
	end
end)

I’m not really sure why that wouldn’t work. The .ChildAdded event doesn’t regulate the .Touched event, meaning if a Bottle is in the array that the for loop is running through and has been touched the event will fire regardless of if a new child has been added.

Why are you not using BottlesFolder for the for loop? Also why are you declaring true in the for loop?

1 Like

you can get rid of the for loop and just use the rest of your code when there is a child added instead of looping through everything, because the loaded parts already have touch listeners from the previous ChildAdded events

1 Like

I thought I should use the for loop to find out all the details in the model and use them in the touch event, but it looks I was wrong

Yes, it worked after I removed the for loop and added what you said, thank you