You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot:如何在游戏运行时通过脚本调用GLTF导出工具?

Godot运行时导出网格为GLTF/OBJ文件方案

关于调用内置Export GLTF工具

Godot编辑器里的Project/Tools/Export GLTF是仅编辑器环境可用的工具,无法在游戏运行时直接调用——这类工具依赖编辑器的专属API,运行时的Godot实例没有权限访问这些接口,所以这条路走不通。

运行时导出GLTF的可行方案

直接用Godot自带的GLTFDocument和GLTFState API实现,完全不需要依赖编辑器工具,代码示例(以Godot 4.x为例):

func export_mesh_to_gltf(mesh_instance: MeshInstance3D, save_path: String) -> Error:
    var gltf_doc = GLTFDocument.new()
    var gltf_state = GLTFState.new()
    
    # 将目标MeshInstance3D添加到GLTF文档中
    gltf_doc.add_node(mesh_instance, gltf_state)
    
    # 写入文件
    var file = FileAccess.open(save_path, FileAccess.WRITE)
    if not file:
        return ERR_CANT_CREATE
    gltf_doc.save_to_buffer(gltf_state)
    file.store_buffer(gltf_doc.get_buffer())
    file.close()
    
    return OK

这个方法能完整导出网格的顶点、材质数据,生成标准GLTF文件,在Godot 3.x中也适用(仅需调整少量API细节,比如文件操作的写法)。

自行编写OBJ生成器的方案

如果只需要基础的网格数据,OBJ格式因为结构简单,自己写导出逻辑也很容易。以下是简化版的顶点+面导出代码:

func export_mesh_to_obj(mesh: Mesh, save_path: String) -> Error:
    var file = FileAccess.open(save_path, FileAccess.WRITE)
    if not file:
        return ERR_CANT_CREATE
    
    # 读取网格表面的顶点数组(仅处理第一个表面,多表面可循环扩展)
    var surface_array = mesh.surface_get_array(0)
    var vertices: Array[Vector3] = []
    # 解析顶点位置(Godot的顶点数组按属性打包,位置在前三个元素)
    for i in range(0, surface_array.size(), mesh.get_array_len()):
        vertices.append(Vector3(surface_array[i], surface_array[i+1], surface_array[i+2]))
    
    # 读取索引数组,无索引则按顺序生成三角面
    var indices: Array[int] = []
    if mesh.surface_get_format(0) & Mesh.ARRAY_FORMAT_INDEX:
        indices = mesh.surface_get_index_array(0)
    else:
        for i in range(0, vertices.size(), 3):
            indices.append(i+1)
            indices.append(i+2)
            indices.append(i+3)
    
    # 写入顶点数据
    for vert in vertices:
        file.store_line("v %.6f %.6f %.6f" % [vert.x, vert.y, vert.z])
    
    # 写入面数据
    for i in range(0, indices.size(), 3):
        file.store_line("f %d %d %d" % [indices[i], indices[i+1], indices[i+2]])
    
    file.close()
    return OK

如果需要导出法线、UV等信息,只需扩展解析对应数组属性即可,适合只需要轻量化网格文件的场景。

内容的提问来源于stack exchange,提问作者Timofei Molokov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:01:13