How to make a part where it gives a player a pet

I want to make a part where you touch it, it gives you a pet.
I’ve tried everything and it keeps saying Attempt to nil index ‘PetInventory’

``local player = game.Players.LocalPlayer
local pets = player.PetInventory

script.Parent.Touched:Connect(function(hit)

local hum = hit.Parent:FindFirstChild("Humanoid")

if hum ~= nil then
	local rat = Instance.new("StringValue")
	rat.Name = "Rat"
	rat.Parent = script.Parent

	local ratClone = rat:Clone()
	ratClone.Parent = pets
end

end)

1 Like
  1. Is this a server script? If it is, you can’t do game.Players.LocalPlayer. You would have to put the variables you defined at the top into the function and set the player variable to game.Players:GetPlayerFromCharacter:(hit.Parent)

  2. Try doing player:WaitForChild(“PetInventory”)

  3. Did you make a folder for PetInventory?

  1. No, this is inside a part.
  2. I have tried it, but it says attempt to nil index ‘WaitForChild’
  3. Yes, its in local player.
1 Like

Maybe try something like this in a regular script in a part?


script.Parent.Touched:Connect(function(hit)

local hum = hit.Parent:FindFirstChild("Humanoid")

local player = game.Players:GetPlayerFromCharacter:(hit.Parent)
local pets = player.PetInventory

if hum ~= nil then
	local rat = Instance.new("StringValue")
	rat.Name = "Rat"
	rat.Parent = pets
end
end)

2 Likes

Thank you so much! It works now.