Ep 22. Other Player’s Pets aren’t Visible

I feel that this issue can best be understood by walking through how to reproduce it:

  1. Player1 joins the game with a Cat pet equipped
  2. Player2 joins the game with a Cat pet equipped
  3. Player1 cannot see Player2’s equipped Pets
  4. Player2 can see Player1’s equipped pets
  5. Player1 rejoins the game and can now see Player2’s equipped Pets

Solution

We need to make some changes to the StarterPlayer/StarterPlayerScripts/PetFollow local script.

In order to fix this issue we need to update the InitializePlayer function to add the new player to the EquippedPets table even if they do not have any pets equipped.

Lua
local function InitalizePlayer(player: Player)
    local pets = EquippedPets[tostring(player.UserId)]
    if not pets then
        EquippedPets[tostring(player.UserId)] = {}
        return
    end
    
    for uuid, pet in pets do
        PetFollow(player, pet)
    end
end

Memory Leak

Along with fixing that issue we can also fix a memory leak which occurs within the same script. This memory leak results from us forgetting to remove players from the EquippedPets table upon leaving. You should add the following code towards the bottom of your script.

Lua
Players.PlayerRemoving:Connect(function(player)
    local pets = EquippedPets[tostring(player.UserId)]
    if pets then
        EquippedPets[tostring(player.UserId)] = nil
    end
end)
Contents