I followed a tutorial about how to make pets but the script keeps giving me an error that says: Workspace.Pet.Script:18: attempt to index nil with 'Position'
here is my code as well:
local pet = script.Parent function givePet(player) if player then local character = player.character if character then local humRootPart local newpet = pet:Clone() newpet.Parent = character local bodyPos = Instance.new('BodyPosition', newpet) bodyPos.MaxForce = Vector3.new(math.huge, math.huge, math.huge) local bodyGyro = Instance.new('BodyGyro', newpet) bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge) while wait()do bodyPos.Position = humRootPart.Position + Vector3.new(2, 2, 3) bodyGyro.CFrame = humRootPart.CFrameend end end end end game.Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(char) givePet(player) end) end)
You're getting this error becuase you defined the bodyposition and bodygyro just in the function. Try to write the variable in the start of the script, and when you have the pet you parent to it. See the example:
local pet = script.Parent local bodyPos = Instance.new("BodyPosition") local bodyGyro = Instance.new("BodyGyro") function givePet(player) if player then local character = player.character if character then local humRootPart local newpet = pet:Clone() newpet.Parent = character bodyPos.Parent = newpet -- Sets the parent of bodyPos -- bodyPos.MaxForce = Vector3.new(math.huge, math.huge, math.huge) bodyPos.Paren = newpet -- Sets the parent of bodyGyro -- bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge) while wait()do bodyPos.Position = humRootPart.Position + Vector3.new(2, 2, 3) bodyGyro.CFrame = humRootPart.CFrameend end end end end game.Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(char) givePet(player) end) end)
When you use local, the variable its on the scope of the if statement, so the script off the scope will see as nil.