CollectionService with a tool

I am trying to use CollectionService to have a variable of the tool no matter what happens to it.

However, the tool seems to be always nil. Even though it is still checked off in the tag window.

https://gyazo.com/64ff99f546afec448f7ece712e502f9c
https://gyazo.com/fd8613b9a707b1de74b687460dc0c0fb

local NightVisions = {}

local function VisionAdded(Tool: Tool)
	NightVisions[Tool] = NightVision.New(Tool)
end

local function VisionRemoved(Tool)
	if NightVisions[Tool] then 
		NightVision:DoCleaning()
		NightVisions[Tool] = nil
	end
end

for _, Tool: Tool in pairs(CollectionService:GetTagged(NightVision.Tag)) do 
	VisionAdded(Tool)
end

NightVisionAdded:Connect(VisionAdded)
NightVisionRemoved:Connect(VisionRemoved)
function NightVision.New(Tool: Tool)
	local self = setmetatable({
		
		_Maid = Maid.new(),
		
		Default = Lighting.OutdoorAmbient,
		NVG = Tool,
		
		Activated = false,
		Cooldown = false,

		ActivationTime = 5,
		CooldownTime = 7,
		
	}, NightVision)
	
	if RunService:IsServer() then 
		print(self.NVG)
		Equip.OnServerEvent:Connect(self.Weld)
		
	elseif RunService:IsClient() then
		
		local Player = game.Players.LocalPlayer
		local Character = PlayerAdded(Player)
		
		print(self.NVG)
		
		self._Maid:GiveTask(
			self.NVG.Activated:Connect(function()
				--	Equip:FireServer(Player)
						
				UserInputService.InputBegan:Connect(function(...)
					self:Pressed(..., self.NVG)
				end)
			end)
		)
		
		local Humanoid = Character:FindFirstChild("Humanoid")

		self._Maid:GiveTask(
			Humanoid.Died:Connect(function()
				self:Removed()
			end)
		)
	end
end

Maybe I am just being stupid, but I am not sure. Any help would be awesome. Thanks.

I am stupid.
I never actually used the tool. I just set it to nil without having it in a player’s backpack.

The problem is I want to do a function when the tool is activated. So, the tool must be in the player’s character, not the backpack. However, it wasn’t working because the tool would be destroyed when the player resets, and it would break the script. Now, I am using CollectionService to tag the tool so it would register when it was destroyed and added again. Unfortunately, what I coded is not working, the tool is always nil.

I fixed it. It was because I will calling .New() on a different script.

1 Like