简体   繁体   English

是什么原因导致Garry的Mod Lua脚本中出现“尝试使用NULL物理对象!”错误?

[英]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 在我删除所有现有的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 . 编辑 :感谢MattJearnes阐明了如何检查gmod对象是否为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. 在不了解gmod的API的情况下,我猜想GetPhysicsObject可以返回一个表示NULL的特殊值,在这种情况下,您无法对其调用ApplyForceCenter You should simply check for NULL before doing anything using IsValid : 您应该在使用IsValid做任何事情之前简单地检查NULL

    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 . 在GMod中,此函数是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. 我会将其添加为对Henrik的回答的评论,但我还没有足够的代表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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