Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 3 years ago

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)
0
Is this a local script or server script? JamiePro248alt 0 — 3y
0
humRootPart is nil Pupppy44 671 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

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.

Ad

Answer this question