In my code I want to print a message whenever a child has been added to the player’s backpack.
The problem is that the Backpack.ChildAdded event is not triggered when I put a tool in the players backpack at run-time
I’ve created the following “serverscript” and stored it under the “ServerScriptService”:
local Players = game:GetService("Players")
local function playerAdded(player)
local backpack = player:WaitForChild("Backpack")
local function printMessage()
print("item added to backpack")
end
backpack.ChildAdded:Connect(printMessage)
end
Players.PlayerAdded:Connect(playerAdded)
First things first check if PlayerAdded event is being triggered becuase sometimes it’s not (when the first player joins the game it is possible that the script is being executed after they join and for that first player in game you have to execute the function you connect manually).
I just double checked and the “PlayerAdded” event is definitely triggered when the player enters the game.
Also, I just noticed that when I put a “ChildAdded” event on the “Workspace” folder it works fine. So the issue just occurs on the player’s “Backpack”
This code works fine:
local Players = game:GetService("Players")
local function playerAdded(player)
local backpack = player:WaitForChild("Backpack")
local function printMessage()
print("item added to Workspace")
end
game.Workspace.ChildAdded:Connect(printMessage)
end
Players.PlayerAdded:Connect(playerAdded)
This code does not work:
local Players = game:GetService("Players")
local function playerAdded(player)
local backpack = player:WaitForChild("Backpack")
local function printMessage()
print("item added to backpack")
end
backpack.ChildAdded:Connect(printMessage)
end
Players.PlayerAdded:Connect(playerAdded)
Any ideas what I’m doing wrong here?
I’ve uploaded the file to hopefully make it easier to troubleshoot: BackpackEventProblem.rbxl (16.6 KB)
I wrote this to check whether the ‘Connection’ is being destroyed after the playerAdded function ends its execution and indeed the connection with the event is being lost. This is something that may help us but I still have not found the solution.
So basically somehow it’s getting disconnected after ‘wait(1)’.
local Players = game:GetService("Players")
local tab = {};
function playerAdded(player)
local backpack = player:WaitForChild("Backpack")
local function printMessage()
print("item added to backpack")
end
local index = #tab + 1;
tab[index] = backpack.ChildAdded:Connect(printMessage);
spawn(function()
while wait() do
print(tab[index].Connected);
end
end)
wait(1);
end
Players.PlayerAdded:Connect(playerAdded)
local Players = game:GetService("Players")
function playerAdded(player)
player.CharacterAdded:Connect(function()
local backpack = player:WaitForChild("Backpack")
local function printMessage()
print("item added to backpack")
end
backpack.ChildAdded:Connect(printMessage);
end)
end
Players.PlayerAdded:Connect(playerAdded)