简体   繁体   中英

What causes “Tried to use a NULL physics object!” error in my Garry's Mod Lua script?

I've made a small script that makes ragdolls fly upwards. It works but it leaves an error message and I cant figure out why.

[ERROR] RunString:11: Tried to use a NULL physics object!  
  1. ApplyForceCenter - [C]:-1  
   2. fn - RunString:11  
    3. unknown - addons/ulib/lua/ulib/shared/hook.lua:179

The error is getting spammed in console until I delete all existing ragdolls

My code:

hook.Add("Think", "Fly", function()

ent = ents:GetAll()

    for k, v in pairs(ent) do
    local isRagdoll = v:IsRagdoll()
        if isRagdoll == true then
        phys = v:GetPhysicsObject()
        phys:ApplyForceCenter(Vector(0, 0, 900))

        end
    end
end)

Thanks in advance.

Edit : Thanks to MattJearnes for clarifying how to check gmod objects for NULL .

Without knowing anything about gmod's API, I'd guess that GetPhysicsObject can return a special value that depicts NULL , in which case you cannot call ApplyForceCenter on it. You should simply check for NULL before doing anything using IsValid :

    hook.Add("Think", "Fly", function()
    ent = ents:GetAll()

    for k, v in pairs(ent) do
        local isRagdoll = v:IsRagdoll()
        if isRagdoll == true then
            local phys = v:GetPhysicsObject()
            if IsValid(phys) then
                phys:ApplyForceCenter(Vector(0, 0, 900))
            end
        end
    end
end)

Henrik's answer is spot on about logic. You do need to make sure the physics object is valid before trying to use it.

In GMod, the function for this is IsValid .

if IsValid(phys) then

I'd have added this as a comment to Henrik's answer but I don't quite have enough rep yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM