Pet system working in studio but not game, help needed

In my game when the player leaves, I save a JSONEncoded table of a player’s pets that are currently equipped. When they join, I JSONDecode the string and equip the pets according to what was saved. This works fine in studio, however, when I play it in the actual game, it errors whenever I join. Here is the code:

local function addPetNecessities(clonedPet, player)
	local character = player.Character
	
	-- Give pet necessities
	for _, child in pairs(script.PetChildren:GetChildren()) do
		local clonedChild = child:Clone()

		if clonedChild:IsA("LocalScript") then
			clonedChild.Disabled = false
		end

		clonedChild.Parent = clonedPet.PrimaryPart
	end
	
	-- Add pet to character
	clonedPet.Parent = character:WaitForChild("Pets")
	
	-- Set network owner to player
	for _, part in pairs(clonedPet:GetDescendants()) do
		if part:IsA("BasePart") then
			part:SetNetworkOwner(player) -- Error line
		end
	end
end

Here is the error I get whenever I join. The function is called with player.CharacterAppearanceLoaded() to ensure the player’s character has loaded, and I use a :WaitForChild() to make sure the pet folder is actually there in workspace.

I am confused at this because I set the pet’s parent to a descendant in workspace, however the error says it is not in workspace.

I have tried many things and still am having trouble to figure out what the issue is. Any help is appreciated, thank you!

FYI:

  • I am using DataStore2 to save the JSONEncoded table in a string.
  • The function is in a ModuleScript and is called in a ServerScript when player.CharacterAppearanceLoaded() is called.
  • Yes, the game is published.
2 Likes

This should work.

--Service--
local Players = game:GetService("Players")
local function addPetNecessities(clonedPet, player)
	local character = player.Character
	local Plr = Players:GetPlayerFromCharacter(character)
	-- Give pet necessities
	for _, child in pairs(script.PetChildren:GetChildren()) do
		local clonedChild = child:Clone()

		if clonedChild:IsA("LocalScript") then
			clonedChild.Disabled = false
		end

		clonedChild.Parent = clonedPet.PrimaryPart
	end

	-- Add pet to character
	clonedPet.Parent = character:WaitForChild("Pets")

	-- Set network owner to player
	for _, part in pairs(clonedPet:GetDescendants()) do
		if part:IsA("BasePart") then
			--need to be a Player Instance
			part:SetNetworkOwner(Plr) -- Error line
		end
	end
end

The error is generated because SetNetworkOwner() , requires a playerInstance.

1 Like

The function includes an argument that already is a player instance.

1 Like

I added a wait(2) before calling the function and it seemed to do the fix, however, I am worried that it will error if a client takes extra long to load. Does anyone know why this would be occurring where player.CharacterAppearanceLoaded() gets called what seems to be too early?