var_to_str
2026/4/14大约 3 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — var_to_str
var_to_str
定义
var_to_str() 用于将任意类型的值序列化为人类可读的文本格式。它和 var_to_bytes() 的作用类似(都是把数据"打包"以便存储或传输),但 var_to_str() 输出的是文字而不是二进制数据。
想象你要把一份菜单发给朋友:var_to_bytes() 像是把菜单用密码本翻译成密码(二进制,人看不懂),var_to_str() 像是直接把菜单拍张照片发过去(文字格式,人能看懂)。
输出的文本格式使用 Godot 特有的序列化语法,可以直接用 str_to_var() 还原回原始数据。
函数签名
C#
// C# 中没有直接等价函数
// 可以手动拼接 JSON 或使用 Json.Stringify
string json = Json.Stringify(Godot.Collections.Dictionary data);GDScript
func var_to_str(variable: Variant) -> String参数说明
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
variable | Variant | 是 | 要序列化的值,支持数字、字符串、数组、字典等基本数据类型 |
返回值
String —— 序列化后的文本字符串。输出的格式是 Godot 特有的文本序列化格式(类似 JSON 但不完全相同)。
代码示例
基础用法:将变量转为文本
C#
using Godot;
public partial class VarToStrExample : Node
{
public override void _Ready()
{
// C# 中使用 Json 类进行类似的文本序列化
var data = new Godot.Collections.Dictionary
{
["name"] = "Godot",
["version"] = 4.6
};
string json = Json.Stringify(data);
GD.Print(json);
// 运行结果: {"name":"Godot","version":4.6}
}
}GDScript
extends Node
func _ready():
# 把不同类型的值转换为文本
print(var_to_str(42)) # 运行结果: 42
print(var_to_str("Hello")) # 运行结果: "Hello"
print(var_to_str(true)) # 运行结果: true
print(var_to_str([1, 2, 3])) # 运行结果: [1, 2, 3]
# 字典序列化
var data = {"name": "Godot", "version": 4.6}
print(var_to_str(data))
# 运行结果: {
# "name": "Godot",
# "version": 4.6
# }实际场景:保存配置到文本文件
C#
using Godot;
public partial class ConfigManager : Node
{
private string ConfigPath => "user://settings.cfg";
public void SaveConfig()
{
var config = new Godot.Collections.Dictionary
{
["resolution_x"] = 1920,
["resolution_y"] = 1080,
["fullscreen"] = true,
["volume"] = 0.8f,
["language"] = "zh-CN"
};
// 使用 JSON 序列化保存到文本文件
string text = Json.Stringify(config, "\t");
using var file = FileAccess.Open(ConfigPath, FileAccess.ModeFlags.Write);
if (file != null)
{
file.StoreString(text);
GD.Print("配置已保存到文本文件");
}
}
public void LoadConfig()
{
using var file = FileAccess.Open(ConfigPath, FileAccess.ModeFlags.Read);
if (file != null)
{
string text = file.GetAsText();
var json = new Json();
Error err = json.Parse(text);
if (err == Error.Ok)
{
var config = (Godot.Collections.Dictionary)json.Data;
GD.Print($"分辨率: {config["resolution_x"]}x{config["resolution_y"]}");
}
}
}
}GDScript
extends Node
var _config_path := "user://settings.cfg"
func save_config() -> void:
var config = {
"resolution_x": 1920,
"resolution_y": 1080,
"fullscreen": true,
"volume": 0.8,
"language": "zh-CN"
}
# 用 var_to_str 序列化为文本
var text = var_to_str(config)
var file = FileAccess.open(_config_path, FileAccess.WRITE)
if file:
file.store_string(text)
file.close()
print("配置已保存到文本文件")
func load_config() -> void:
var file = FileAccess.open(_config_path, FileAccess.READ)
if file:
var text = file.get_as_text()
file.close()
# 用 str_to_var 反序列化
var config = str_to_var(text)
print("分辨率: %dx%d" % [config["resolution_x"], config["resolution_y"]])进阶用法:调试输出复杂数据结构
C#
using Godot;
public partial class DebugDumper : Node
{
public override void _Ready()
{
var gameState = new Godot.Collections.Dictionary
{
["players"] = new Godot.Collections.Array
{
new Godot.Collections.Dictionary { ["name"] = "勇者", ["hp"] = 100 },
new Godot.Collections.Dictionary { ["name"] = "法师", ["hp"] = 80 }
},
["turn"] = 3,
["weather"] = "雨天"
};
GD.Print("=== 游戏状态 ===");
GD.Print(Json.Stringify(gameState, " "));
}
}GDScript
extends Node
func _ready():
var game_state = {
"players": [
{"name": "勇者", "hp": 100},
{"name": "法师", "hp": 80}
],
"turn": 3,
"weather": "雨天"
}
print("=== 游戏状态 ===")
print(var_to_str(game_state))
# 运行结果:
# === 游戏状态 ===
# {
# "players": [
# {
# "name": "勇者",
# "hp": 100
# },
# {
# "name": "法师",
# "hp": 80
# }
# ],
# "turn": 3,
# "weather": "雨天"
# }注意事项
与
var_to_bytes()的区别:var_to_str()输出人类可读的文本,文件更大但可以用文本编辑器查看和修改。var_to_bytes()输出紧凑的二进制数据,文件更小但无法直接查看。选择哪种取决于你的需求。格式不是标准 JSON:
var_to_str()输出的格式类似 JSON 但有差异(比如数字格式、空值的表示方式等)。如果需要标准 JSON 格式,请使用JSON.stringify()和JSON.parse()。必须与
str_to_var()配对:用var_to_str()序列化的文本,必须用str_to_var()来还原。不能混用其他反序列化方式。C# 中推荐使用 JSON:C# 中没有
var_to_str()的直接等价。推荐使用Json.Stringify()和Json.Parse()来实现类似功能。
