Hello guys!
I’m trying to detect if a pet is added to the character but my script doesn’t work but i don’t understand why.
My script is a local script In the starterPack
My script is :
local Players = game:GetService("Players")
local rs = game:GetService("ReplicatedStorage")
local event = rs:WaitForChild("Remotes"):WaitForChild("NewPetEquipped")
local plr = Players.LocalPlayer
local char = plr.Character
char.ChildAdded:Connect(function(instance)
if instance.Name == plr.Name.." 's Pet1" or plr.Name.." 's Pet2" then
event:FireServer(instance.Name, "add")
end
end)
char.ChildRemoved:Connect(function(instance)
if instance.Name == plr.Name.." 's Pet1" or plr.Name.." 's Pet2" then
event:FireServer(instance.Name, "remove")
end
end)
And here is my output:
23:44:15.479 - Players.Padrox_x.Backpack.PetDetect:8: attempt to index nil with 'ChildAdded'
23:44:15.480 - Stack Begin
23:44:15.480 - Script 'Players.Padrox_x.Backpack.PetDetect', Line 8
23:44:15.481 - Stack End
You need to ensure that the character gets loaded in before connecting it to the events, also I recommend you use starter character scripts since this script will not work after the character dies once. Anyways to get your current solution to work you should modify this line:
local char = plr.Character
--to:
local char = plr.Character or plr.CharacterAdded:Wait()
Remember than this will not work after the player dies as i said earlier so what i recommend you do is create a local script and place it in starter character scripts like this:
local event = rs:WaitForChild("Remotes"):WaitForChild("NewPetEquipped")
local char = script.Parent -- starter character scripts get parented to the character model
char.ChildAdded:Connect(function(instance)
if instance.Name == plr.Name.." 's Pet1" or plr.Name.." 's Pet2" then
event:FireServer(instance.Name, "add")
end
end)
char.ChildRemoved:Connect(function(instance)
if instance.Name == plr.Name.." 's Pet1" or plr.Name.." 's Pet2" then
event:FireServer(instance.Name, "remove")
end
end)