Skip to content

对象模块管理接口 GameObject

具体函数名及描述如下:

序号函数名函数描述
1FindObject(...)根据ID查找游戏对象
2FindUIObject(...)获取当前游戏ui对象
3CreatePrefabInst(...)创建预制实例
4CreatePrefab(...)创建对象
5Destroy(...)删除对象

FindObject

  • 参数及类型:
    • id:number,string游戏对象的唯一标识
  • 返回值及类型:
    • ret:GameObject,nil返回找到的游戏对象,如果没有找到则返回nil
  • 该方法的主要作用: 根据ID查找游戏对象
  • 具体使用案例如下:
lua
    local uiObj = GameObject:FindObject("7482986899365911542-22886")

    if uiObj then

        print("找到ui界面对象")

    end

    local hostUin = Player:GetHostUin()

    local player = GameObject:FindObject(hostUin)

    if player then

        print("找到玩家对象")

    end

FindUIObject

  • 参数及类型:
    • id:number,string游戏对象的唯一标识
  • 返回值及类型:
    • ret:GameObject,nil返回查找的ui对象,如果没有找到则返回nil
  • 该方法的主要作用: 获取当前游戏ui对象
  • 具体使用案例如下:
lua
local ret = GameObject:FindUIObject(id)

CreatePrefabInst

  • 参数及类型:
    • prefabId:number,string预制体ID
    • mapId:number星球ID(传nil)
    • x:number位置X坐标
    • y:number位置Y坐标
    • z:number位置Z坐标
    • trigger:boolean是否触发事件
  • 返回值及类型:
    • ret:GameObject,nil返回创建的对象,如果创建失败则返回nil
  • 该方法的主要作用: 创建预制实例
  • 具体使用案例如下:
lua
    -- 创建场景中对象类型预制

    local obj = GameObject:CreatePrefabInst("r1_7482990429829028854_22890", nil, 10,8,10)

    if obj then

        local hpCmp = obj:GetComponent("HP") -- 获取血量组件

        if hpCmp then

            hpCmp.hp = 120 -- 设置血量

        end

        print("创建预制成功")

    end

CreatePrefab

  • 参数及类型:
  • 返回值及类型:
    • ret:GameObject,nil返回创建的对象,如果创建失败则返回nil
  • 该方法的主要作用: 创建对象
  • 具体使用案例如下:
lua
    -- 创建游戏内预设的生物2只

    local objs = GameObject:CreatePrefab(ObjType.Mob, 3400, 10,8,10, 2)

    if objs and #objs > 0 then

        -- prefab.transform:SetPosition(10,8,10) -- 设置位置, 等同上面创的位置参数操作

        for _, prefab in ipairs(objs) do

            local hpCmp = prefab:GetComponent("HP") -- 获取血量组件

            if hpCmp then

                hpCmp.hp = 120 -- 设置血量

            end

        end

        print("创建游戏内生物成功")

    end

    -- 创建自定义生物 1只

    local customObjs = GameObject:CreatePrefab(ObjType.Mob, "r1_7482990429829028854_22890", 10,8,13, 1)

    if customObjs and #customObjs > 0 then

        print("创建自定义生物成功")

    end

Destroy

  • 参数及类型:
  • 返回值及类型:
    • ret:bool成功(true)
  • 该方法的主要作用: 删除对象
  • 具体使用案例如下:
lua
    local obj = GameObject:CreatePrefabInst("r1_7482990429829028854_22890", nil, 10,8,10)

    if obj then

        -- 删除对象

        GameObject:Destroy(obj:GetId())

        -- obj:Destroy() 对象的也可以直接调用Destroy删除

    end