ToolTracker – Reliable, Deterministic Tool Lifecycle Tracking

Full Source Code
--!strict
--[[
	ToolTracker: Finite State Machine for Tool Parent Changes

	This module tracks Tools in a player’s Backpack and Character, and emits
	events when their "parent state" changes. State is derived solely from
	the Tool's Parent:

		Backpack  → in the player’s Backpack
		Character → in the player’s Character
		Other     → any other location (workspace, nil, destroyed, etc.)

	Transitions are detected via ChildAdded and ChildRemoved events.
	Events are fired only when a Tool moves between states. Some transitions
	emit multiple events, in the following order:

	Transition Table (Old → New):

	Backpack (B)
		B → B : none
		B → C : ToolEquipped
		B → O : ToolRemoved

	Character (C)
		C → C : none
		C → B : ToolUnequipped
		C → O : ToolUnequipped, then ToolRemoved

	Other (O)
		O → O : none
		O → B : ToolAdded
		O → C : ToolAdded, then ToolEquipped

	Lifecycle:
		- Call StartTracking(backpack, character) to begin.
		- Calling StartTracking again resets tracking to new containers.
		- Destroy stops tracking permanently and cleans up events.
]]

local ToolParentState = { Backpack = 1, Character = 2, Other = 3 }
export type ToolParentState = number

local function resolveParentState(self: ToolTracker, tool: Tool): ToolParentState
	return
		if tool.Parent == self._backpack then ToolParentState.Backpack
		elseif tool.Parent == self._character then ToolParentState.Character
		else ToolParentState.Other
end

local function applyParentTransition(self: ToolTracker,
	tool: Tool, oldState: ToolParentState, newState: ToolParentState)

	if oldState == ToolParentState.Backpack then

		if newState == ToolParentState.Character then
			self._toolEquippedEvent:Fire(tool)
		elseif newState == ToolParentState.Other then
			self._toolRemovedEvent:Fire(tool)
		end

	elseif oldState == ToolParentState.Character then

		if newState == ToolParentState.Backpack then
			self._toolUnequippedEvent:Fire(tool)
		elseif newState == ToolParentState.Other then	
			self._toolUnequippedEvent:Fire(tool)
			self._toolRemovedEvent:Fire(tool)
		end

	elseif oldState == ToolParentState.Other then

		if newState == ToolParentState.Backpack then
			self._toolAddedEvent:Fire(tool)
		elseif newState == ToolParentState.Character then
			self._toolAddedEvent:Fire(tool)
			self._toolEquippedEvent:Fire(tool)
		end

	end	
end

local function processParentChange(self: ToolTracker, tool: Instance)
	if not tool:IsA("Tool") then
		return
	end

	local oldState = self._toolParentMap[tool] or ToolParentState.Other
	local newState = resolveParentState(self, tool)

	if oldState ~= newState then -- Guards against double fires (C -> B or B -> C)
		applyParentTransition(self, tool, oldState, newState)
		self._toolParentMap[tool] =
			if newState ~= ToolParentState.Other then newState else nil -- Update or cleanup
	end
end

local function observeContainer(self: ToolTracker, container: Backpack | Model)
	table.insert(self._connections,
		container.ChildAdded:Connect(function(child)
			processParentChange(self, child)
		end)
	)
	table.insert(self._connections,
		container.ChildRemoved:Connect(function(child)
			processParentChange(self, child)
		end)
	)
end

local function initializeTracking(self: ToolTracker, backpack: Backpack, character: Model)
	-- Update references
	self._backpack = backpack
	self._character = character
	
	-- Initial scans
	for _, child in backpack:GetChildren() do
		processParentChange(self, child)
	end

	for _, child in character:GetChildren() do
		processParentChange(self, child)
	end

	-- Bind events
	observeContainer(self, backpack)
	observeContainer(self, character)
end

local function stopTracking(self: ToolTracker)
	for _, conn in self._connections do
		conn:Disconnect()
	end
	table.clear(self._connections)
	table.clear(self._toolParentMap)
	self._backpack, self._character = nil, nil
end

--[[
    ----------------------------------------------------------------------------
	-<[ PUBLIC ]>---------------------------------------------------------------
	----------------------------------------------------------------------------
]]

local ToolTracker = {}
ToolTracker.__index = ToolTracker

export type ToolTracker = typeof(ToolTracker.new())

function ToolTracker.new()
	
	local toolAddedEvent = Instance.new("BindableEvent")
	local toolRemovedEvent = Instance.new("BindableEvent")
	local toolEquippedEvent = Instance.new("BindableEvent")
	local toolUnequippedEvent = Instance.new("BindableEvent")

	local self = setmetatable({

		_backpack  = nil :: Backpack?,
		_character = nil :: Model?,

		_toolParentMap = {} :: {[Tool]: ToolParentState?},
		_connections   = {} :: {RBXScriptConnection},
		
		_toolAddedEvent = toolAddedEvent,
		ToolAdded = toolAddedEvent.Event,

		_toolRemovedEvent = toolRemovedEvent,
		ToolRemoved = toolRemovedEvent.Event,

		_toolEquippedEvent = toolEquippedEvent,
		ToolEquipped = toolEquippedEvent.Event,

		_toolUnequippedEvent = toolUnequippedEvent,
		ToolUnequipped = toolUnequippedEvent.Event,

	}, ToolTracker)

	return self	
end

function ToolTracker.StartTracking(self: ToolTracker, backpack: Backpack, character: Model)
	-- Sanity checks
	assert(backpack and backpack:IsA("Backpack"), "StartTracking: first argument must be a valid Backpack instance")
	assert(character and character:IsA("Model"), "StartTracking: second argument must be a valid Model (usually a Character)")

	-- Cleanup if needed
	stopTracking(self)

	-- Init
	initializeTracking(self, backpack, character)
end

function ToolTracker.GetTrackedTools(self: ToolTracker): {Tool?}
	local result = {}
	for tool, _ in self._toolParentMap do
		table.insert(result, tool)
	end
	return result
end

function ToolTracker.Destroy(self: ToolTracker)
	if self._backpack == nil and self._character == nil then
		-- Already destroyed / never started, quiet success
		return
	end
	
	stopTracking(self)

	self._toolAddedEvent:Destroy()
	self._toolRemovedEvent:Destroy()
	self._toolEquippedEvent:Destroy()
	self._toolUnequippedEvent:Destroy()

	setmetatable(self, nil)
end

return ToolTracker

ToolTracker: Deterministic Tool Lifecycle Tracking

Tracking Tool instances reliably between a player’s Backpack and Character requires careful handling of container transitions. Approaches that combine multiple independent signals (ChildAdded, ChildRemoved, Tool.Equipped, Tool.Unequipped) frequently encounter false events, ordering inconsistencies, and edge-case failures during respawns, drops, or manual reparenting.

ToolTracker formalizes the problem as a finite state machine whose only input is the Tool’s Parent. From these container changes it emits four deterministic lifecycle events with strict guarantees on ordering and pairing.


Overview

The module maintains an internal three-state model for each tool:

State Meaning
Backpack Tool resides in the player’s Backpack
Character Tool resides in the player’s Character
Other Tool is elsewhere (Workspace, nil, destroyed…)

All event emission is derived exclusively from ChildAdded/ChildRemoved on the two containers. No per-tool connections or Tool signals are used.


Features

  • Four lifecycle events: ToolAdded, ToolRemoved, ToolEquipped, ToolUnequipped
  • Guaranteed event ordering and pairing (ToolAdded is always eventually followed by ToolRemoved)
  • Full support for drops (CanBeDropped), respawns, manual reparenting, and destruction
  • Zero reliance on Tool.Equipped or Tool.Unequipped
  • ~100 lines, fully typed (–!strict), no memory leaks
  • Compatible with both server and client

Quick Start

local ToolTracker = require(game.ReplicatedStorage.ToolTracker)

local tracker = ToolTracker.new()

tracker.ToolAdded:Connect(function(tool: Tool)
	print(tool.Name, "added to inventory")
end)

tracker.ToolEquipped:Connect(function(tool: Tool)
	print(tool.Name, "equipped")
end)

tracker.ToolUnequipped:Connect(function(tool: Tool)
	print(tool.Name, "unequipped")
end)

tracker.ToolRemoved:Connect(function(tool: Tool)
	print(tool.Name, "removed or dropped")
end)

-- Bind listeners *before* starting tracking to capture initial state
tracker:StartTracking(player.Backpack, player.Character)

-- Recommended pattern for respawns
player.CharacterAdded:Connect(function(character: Model)
	tracker:StartTracking(player.Backpack, character)
end)

Event Semantics

The transition table below defines every possible emission:

Old State New State Events Fired
Backpack Character ToolEquipped
Backpack Other ToolRemoved
Character Backpack ToolUnequipped
Character Other ToolUnequipped, ToolRemoved
Other Backpack ToolAdded
Other Character ToolAdded, ToolEquipped

All other transitions (including self-transitions) produce no events.


API Reference

Constructor

local tracker = ToolTracker.new()

StartTracking

tracker:StartTracking(backpack: Backpack, character: Model)

Begins observation. Calling again resets tracking to the new containers.

GetTrackedTools

local tools: { Tool } = tracker:GetTrackedTools()

Returns every tool currently inside the tracked Backpack or Character.

Destroy

tracker:Destroy()

Stops all observation, destroys internal events, and renders the instance unusable.


Implementation Notes

  • State is derived solely from Parent equality; no additional signals are attached.
  • Double-firing protection prevents duplicate events during rapid container swaps.
  • Cleanup on Destroy is complete and idempotent.
  • The module is intentionally minimal and makes no assumptions about your broader architecture.

Feedback and questions are welcome.

3 Likes