Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

I keep getting this error in my pet script that I got from a tutorial, can anyone help me?

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)

2 comments

0

Is this a local script or server script?

0

humRootPart is nil

1 answer

✓ Accepted answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.