@tool extends Node2D @export var export_dir_root := "res://asset/art/ui/note/" @export var json: JSON # can be a JSONParseResult or a Dictionary @export var texture: Texture2D @export_tool_button("执行") var execute = _run @export var demo_scale := 0.5 @export_tool_button("刷新 demo") var refresh = _refresh_demo var export_dir func _run() -> void: if not json or not texture: printerr("JSON 或 texture 未设置") return if not export_dir_root: push_error("导出目录未设置") return export_dir = export_dir_root + ("" if export_dir_root.ends_with("/") else "/") export_dir = export_dir + json.resource_path.get_file().split(".")[0] + "/" print("导出目录: ", export_dir) # 确保导出目录存在 DirAccess.make_dir_recursive_absolute(export_dir) # 解析 JSON 数据 var data: Dictionary if json: data = json.data # 检查 meta.slices if not data.has("meta") or not data.meta.has("slices"): push_error("JSON 中缺少 meta.slices") return for slice_dict in data.meta.slices: var slice_name = slice_dict.get("name", "") var keys = slice_dict.get("keys", []) if slice_name == "" or keys.is_empty(): continue var key = keys[0] var bounds = key.get("bounds", null) if typeof(bounds) != TYPE_DICTIONARY: continue var rect := Rect2( bounds.get("x", 0), bounds.get("y", 0), bounds.get("w", 0), bounds.get("h", 0) ) _create_and_save_atlas(slice_name, rect) print("已导出 Atlas: ", slice_name, " at ", export_dir) func _create_and_save_atlas(atlas_name: String, region: Rect2) -> void: var path = export_dir + atlas_name + ".tres" var atlas_res: AtlasTexture if FileAccess.file_exists(path): atlas_res = load(path) print_rich("[color=cyan]加载已有的 Atlas: ", path) if not atlas_res: atlas_res = AtlasTexture.new() atlas_res.resource_path = path print_rich("[color=green]创建新的 Atlas: ", path) atlas_res.atlas = texture atlas_res.filter_clip = true atlas_res.region = region # 修正了原来拼写错误的 regoin ResourceSaver.save(atlas_res, path) func _refresh_demo() -> void: var demo_node = $Demo for c in demo_node.get_children(): c.queue_free() # 将 export_dir 下的 texture 显示在 demo 下,彼此保持 200*200 距离 var x_offset = 0 var y_offset = 0 for file_name in DirAccess.get_files_at(export_dir): if file_name.ends_with(".tres"): var path = export_dir + file_name var res = load(path) if res is AtlasTexture: var sprite = Sprite2D.new() sprite.texture = res sprite.position = Vector2(x_offset, y_offset) sprite.scale = Vector2(demo_scale, demo_scale) demo_node.add_child(sprite) x_offset += 200 if x_offset > 1000: x_offset = 0 y_offset += 200