Lua中判断引用的C#对象是否为空

Lua中判断引用的C#对象是否为空

现象
我们在游戏中经常使用lua引用C#中的一个对象,当我们试图使用C#中的方法删除这个对象时,lua中并不知道这个对象已经被删除了,这时我们再去使用这个lua对象做一些操作时就会报错。
原理
在Lua/System/Global.lua里面提供了很多实用的函数集合,里面其中有一个函数是
–unity 对象判断为空, 如果你有些对象是在c#删掉了,lua 不知道
–判断这种对象为空时可以用下面这个函数。
function IsNil(uobj)
return uobj == nil or uobj:Equals(nil)
end
通过它来判定当前对象是否已经被c#删除掉了,还有值得一提的是如果是userdata数据类型对象,需要用 == nil来判定~
测试程序

function DGS_TestMgr:Test2()
    --W按键

    local GameObject =  UnityEngine.GameObject;
    local obj = GameObject('TestGo');  

    local node = obj.transform;  
    node.position = Vector3.one;  
    GameObject.Destroy(obj);

    if not obj then
        print('not obj --->' .. 'obj is nil.')
    else
        print('not obj --->' .. 'obj is not nil.')
    end
    if obj == nil then
        print('obj == nil --->' .. 'obj is nil.')
    else
        print('obj == nil --->' .. 'obj is not nil.')
    end
    if obj:Equals(nil) then  
        print('obj:Equals(nil) --->' .. 'obj is nil.')
    else
        print('obj:Equals(nil) --->' .. 'obj is not nil.')
    end  

end

测试结果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_34907362/article/details/80482493