Attempting to loop a for in pairs loop

  1. What do you want to achieve?
    I want to be able to make a for _,i in pairs() do thing in workspace constantly be checking/looping. The script is in ServerScriptService and is meant to handle boxes that give you items when touched.

  2. What is the issue?
    I have zero idea on how to make this, I have searched. What I have tried has resulted in duplicates of items.

  3. What solutions have you tried so far?
    RunService, while loops, repeat until, ChildAdded, ChildRemoved, etc. None worked for me.

Here is my current script:

local players = game:GetService("Players")
local Serverstorage = game:GetService("ServerStorage")
local items = Serverstorage.Tools.Guns:GetChildren()

for _,item in pairs(workspace:GetDescendants()) do
	if item.Name == "ItemBox" and item:IsA("BasePart") then
		item.Touched:Connect(function(hit)
			local db = false
			if hit.Parent.ClassName == "Model" and hit.Parent:FindFirstChild("Humanoid") and players:FindFirstChild(hit.Parent.Name) then
				
				if db ~= false then return end
				db = true
				
				local backpack = players[hit.Parent.Name]:FindFirstChild("Backpack")
				local item2 = items[math.random(1,#items)]:Clone()
				item2.Parent = backpack
				
				print("please")
				
				item:Destroy()
					
			end
		end)
	end
end
1 Like

Hi Rusty_Lightswitch,

If you’re just connecting a Touched signal to any ‘ItemBoxes’ that will enter the workspace, consider using
CollectionService (which has an example of your scenario) to listen for newly added Instances.

local function OnItemBoxTouched(otherInstance)
-- the item logic
end

-- This will Connect() the Touched signal to any new ItemBoxes with the matching tag
CollectionService:GetInstanceAddedSignal("TAG_ITEM_BOX"):Connect(function(itemBox)
     itemBox.Touched:Connect(OnItemBoxTouched)
end)

You will have to add some ItemBox:AddTag() logic to whatever is spawning your ItemBoxes in order for CollectionService to pick up on them

4 Likes

Hello,

I did this and it works well, but the problem is if a new instance of the box is added to the game, it won’t work. What I am trying to do is whenever there is a new box it will be able to work.

Could in a folder in workspace do or workspace itself use the .ChildAdded and check if the what was added was a box than connect it.

The above solution should work much better tho

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