【踩坑】Xlua中GetComponent获取组件返回值不是nil

      好久没写东西了,因为疫情原因摸了好久的鱼,最近也没做什么有意思的东西,就随便记点最近踩到的坑吧~
      项目组最近使用Xlua进行开发,其实说实话Xlua,tolua对于我这种拼UI的辣鸡程序来说没啥区别,但是今天踩到了一个Xlua里getComponent的坑:我在lua中通过getComponent获取组件信息的时候,Image和Text组件拿到的都是nil,而canvas拿到的却是一个值为nil:0的userdata。

    local image = go and global_getComponent(go, "Image")
    local text = go and global_getComponent(go, "Text")
    local canvas = go and global_getComponent(go, "CanvasGroup")
    print(type(text), text)
    print(type(canvas), canvas)

      输出值为:

nil 
userdata    null: 0 

      当时我就震惊了,后来查阅资料看到,原来可能是unity获取组件失败不给我返回一个null,而是返回一个可以判断出是null的object?!然后在C#端可以判null,在lua就不行了!!!
      资料里写的方法是修改ObjectTranslator脚本中的push函数,添加object的判空o.Equals(null)进行解决的。但是我们这边的代码因为有封装过一层获取组件的接口:

    public static Component GetComponent(GameObject _go, string _compname)
    {
        if (_go == null)
            return null;
        Type t = GetComponentType(_compname);

        if (null == t)
        {
            DebugManager.DebugError("component class not find: " + _compname);
            return null;
        }
        //retrutn _go.GetComponent(t);
        var resultCom = _go.GetComponent(t);
        if (resultCom == null)
            return null;
        else
            return resultCom;
    }

      GetComponentType其实就是一个字典集,实现可以从字符串映射到type类型的功能,之前我们直接返回了GetComponent的结果,经过我自作聪明的XJB改,多了一层判空,也就是相当于在C#层对这个对象进行判空,然后再传递给lua,这样也可以解决这个问题!

你可能感兴趣的:(【踩坑】Xlua中GetComponent获取组件返回值不是nil)