generated at
Godot: SpreadSheet から CSV出力したファイルをDictonaryとして読み込む
アイテムや敵のマスタデータなどをSpreadsheetで管理したい
そしてGodot Engine側では、Dictionary型としてインポートして管理したい
こちらのソースコードを参考にした:GitHub - Anaxie-Studio/godot-csv-to-dictionary
Array 型もサポートするため、コードを追加
環境はGodot 4.0で確認


例えば、以下のようなデータを用意して
id プロパティを key とし、value は更に他のプロパティを key:value として Object型を格納したい。以下のようなDict
godot
const UPGRADES = { "arrow1": { "icon": WEAPON_PATH + "arrow.png", "name": "Arrow", "level": 1, "description": "矢をランダムな敵に発射する", "required": [], "type": "weapon" }, "arrow2": { "icon": WEAPON_PATH + "arrow.png", "name": "Arrow", "level": 2, "description": "発射する矢が追加", "required": ["arrow1"], "type": "weapon" },

SpreadSheet のデータを csv エクスポートして、拡張子を.txt ファイルに変更
こうしないと、Godot が csv 拡張子のファイルは翻訳ファイルと認識して別のインポート処理が走ってしまう
Godot のプロジェクト配下に txt ファイルを移動
この操作は自動化したい
以下のコードで parse し、シングルトン等で保持する
py
func parse( file_path: String, id_column: String = "id", delimiter: String = "," ) -> Dictionary: if not FileAccess.file_exists(file_path): printerr("file path %s is not exist" % file_path) return {} var file := FileAccess.open(file_path, FileAccess.READ) var dict_data: Dictionary = {} var line_index: int = -1 var column_headers := [] while not file.eof_reached(): line_index += 1 var line := file.get_csv_line(delimiter) if line_index == 0: column_headers = line continue var entry: Dictionary = {} for column_index in column_headers.size(): var value = line[column_index] if value is String: var value_lower: String = value.to_lower() # Detect bools. if value_lower == "true": value = true elif value_lower == "false": value = false # Detect Arrays if value_lower.begins_with("[") and value_lower.ends_with("]"): value_lower = value_lower.trim_prefix("[").trim_suffix("]") var split_array_values = [] for split_value in value_lower.split(","): split_array_values.push_back(split_value.trim_prefix(" ").trim_suffix(" ")) value = split_array_values entry[column_headers[column_index]] = value if column_headers[column_index] == id_column: dict_data[entry[id_column]] = entry file.close() return dict_data