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

Error with BodyPosition in my fly script? (Attempt to index nil with 'Position')

Asked by 4 years ago
Edited 4 years ago

Hello,

I have a fly script that makes you fly when you double press space, but there is an error on line 31 that I can't understand. (Error: Players.DoudGeorges.Backpack.FlyScript:31: attempt to index nil with 'Position').

Here is the script:

local uis = game:GetService("UserInputService")
local rs = game:GetService("RunService")

local myPlayer = game.Players.LocalPlayer
local myChar = myPlayer.Character or myPlayer.CharacterAdded:Wait()
local myHRP = myChar:FindFirstChild("HumanoidRootPart")
local camera = game.Workspace.CurrentCamera

local flying = false
local speed = 0.5

local TapTime = .25
local Tapped = false


local bp = Instance.new("BodyPosition", myHRP)
bp.MaxForce = Vector3.new()
bp.D = 10
bp.P = 10000

local bg = Instance.new("BodyGyro", myHRP)
bg.MaxTorque = Vector3.new()
bg.D = 10

function fly()
    flying = true
    bp.MaxForce = Vector3.new(400000,400000,400000)
    bg.MaxTorque = Vector3.new(400000,400000,400000)
    while flying do
        rs.RenderStepped:wait()
        bp.Position = myHRP.Position +((myHRP.Position - camera.CFrame.p).unit * speed)
        bg.CFrame = CFrame.new(camera.CFrame.p, myHRP.Position)
    end
end

function endFlying()
    bp.MaxForce = Vector3.new()
    bg.MaxTorque = Vector3.new()
    flying = false
end

uis.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.Space then
        if not Tapped then
            Tapped = true
            wait(TapTime)
            Tapped = false
        else
            if not flying then
                fly()
            else
                endFlying()
            end
        end
    end
end)

Thanks for your help!!

0
I'm not gonna post this as an answer, as idk if it is the reason MrCatDoggo 213 — 4y
0
with your local myHRP should be a :WaitForChild("HumanoidRootPart", 20) instead MrCatDoggo 213 — 4y

1 answer

Log in to vote
1
Answered by
RAFA1608 543 Moderation Voter
4 years ago
Edited 4 years ago

In line 31, there isn't any checking if the body position still exists. Check if it still exists, like this:

if bp then
    bp.Position = myHRP.Position +((myHRP.Position - camera.CFrame.p).unit * speed)
end

Or, wrap it in a pcall, if the checking above doesnt work.

pcall(function() --Use this instead if the nil-checking doesnt work.
    bp.Position = myHRP.Position +((myHRP.Position - camera.CFrame.p).unit * speed)
end)

Basically, what the error Players.DoudGeorges.Backpack.FlyScript:31: attempt to index nil with 'Position' means, is that the bodyposition doesnt exist anymore. Hope this helped.

0
your forgetting theres multiple positions. i think the problem may more be with myhrp MrCatDoggo 213 — 4y
Ad

Answer this question