How do I make one script control all the tools in my game?

So I have been trying to have one script control all my tools in the game instead of a bunch of scripts in each tool. I’ve got it to detect the tool and detect when the tool is activated, but if there is more than one tool in the player’s inventory and they click both for some reason the tool activation runs twice. Here is the code below, I would love feedback on what I can do differently and any changes that might help!

P.S. the removeTool function is meant to be used later for durability please ignore it

--//Services\\--
local Players = game:GetService("Players")
local repStorage = game:GetService("ReplicatedStorage")

--//Asset Related\\--
local assets = repStorage.Assets

local anims = assets.Anims
local sounds = assets.Sounds
local toolAnims = anims.Tools

--//PlayerHandler\\--
Players.PlayerAdded:Connect(function(plr)
	
	--//Character Handler\\--
	plr.CharacterAdded:Connect(function(char)
		
		local hum = char:WaitForChild("Humanoid")
		local animator = hum:WaitForChild("Animator")
		
		char.ChildAdded:Connect(function(tool)
			
			local function removeTool()

				if plr.Backpack:FindFirstChild(tool) then

					plr.Backpack.tool:Destroy()

				else

					tool:Destroy()

				end

			end
			
			if tool:IsA("Tool") and tool.Name == "Food" then
				
				local debounce = false
				
				local cooldown = tool:GetAttribute("cooldown")
				
				tool.Activated:Connect(function()
					
					if debounce == false then
						
						debounce = true
						
						print("e")
						task.wait(cooldown)
						
						debounce = false
					end
					
				end)
				
			end
			
			--//tool script ends here
		end)
		
	end)
end)

One connection is created to do the same thing for every tool that is named “Tool” or “Food” in the player’s character. I also don’t see any method for disconnecting the event when they unequip the tool.
Ask yourself what you’re trying to solve by having this all be in one script. Once you get to the point where you have to figure out which character did what, you’ll be passing a bunch of things back and forth to this function. If each tool had its own script that information would be easily found based on where the script is running from.

2 Likes

Couldn’t you just use CollectionService instead of doing all this for loop stuff?

You can? Do you have a link to the article?

Yeah. You could loop through CollectionService:Get tagged(“TagName”)

Alright I’ll look into it and close this, thank you!

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