如果我想序列化戈多中的数组,我可以这样做:
var a1 = [1 ,2 ,3]
# save
var file = File.new()
file.open("a.sav", File.WRITE)
file.store_var(a1, true)
file.close()
# load
file.open("a.sav", File.READ)
var a2 = file.get_var(true)
file.close()
print(a1)
print(a2)产出(按预期工作):
[1, 2, 3]
[1, 2, 3]但是,如果我想序列化一个对象,比如A.gd中的这个类:
class_name A
var v = 0使用A实例进行相同的测试
# instance
var a1 = A.new()
a1.v = 10
# save
var file = File.new()
file.open("a.sav", File.WRITE)
file.store_var(a1, true)
file.close()
# load
file.open("a.sav", File.READ)
var a2 = file.get_var(true)
file.close()
print(a1.v)
print(a2.v)产出:
10错误(在线print(a2.v)):
Invalid get index 'v' (on base: 'previously freed instance').网上文档:
void store_var(value: Variant, full_objects: bool = false)
Stores any Variant value in the file. If full_objects is true, encoding objects is allowed (and can potentially include code).
Variant get_var(allow_objects: bool = false) const
Returns the next Variant value from the file. If allow_objects is true, decoding objects is allowed.
Warning: Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.它不应该适用于full_objects=true吗?否则,这个参数的用途是什么?
我的类包含许多数组和其他东西。我猜戈多会处理这种基本的序列化功能(当然,devs有时需要保存复杂的数据),所以,也许我只是没有做我应该做的事情。
有什么想法吗?
发布于 2021-07-28 22:30:22
要使full_objects工作,您的自定义类型必须从Object扩展(如果不指定类扩展的内容,则扩展Reference)。然后,序列化将基于导出的变量(或您在_get_property_list中所说的任何内容)。顺便说一句,这可以序列化定制类型的整个脚本,在您的情况下也可能是这样。您可以通过查看保存的文件来验证。
因此,full_objects对序列化扩展Resource (不扩展Object)的类型没有用处。相反,Resource序列化与ResourceSaver和ResourceLoader一起工作。还有load和preload__。是的,这就是如何存储或加载场景、脚本(以及纹理和网格,等等…)。。
我认为您的代码的更简单的解决方案是使用函数str2var和var2str。这会让你省去很多头痛:
# save
var file = File.new()
file.open("a.sav", File.WRITE)
file.store_pascal_string(var2str(a1))
file.close()
# load
file.open("a.sav", File.READ)
var a2 = str2var(file.get_pascal_string())
file.close()
print(a1.v)
print(a2.v)不管您存储的是什么,该解决方案都会工作。
发布于 2021-10-16 22:18:38
也许这是一个解决方案(我还没有测试)
# load
file.open("a.sav", File.READ)
var a2 = A.new()
a2=file.get_var(true)
file.close()
print(a1.v)
print(a2.v)https://stackoverflow.com/questions/68567355
复制相似问题