什么是持久数据以及如何使用它
persistentData 是玩家、世界和服务器上可用的 NBT 复合标签对象。
它对于简单的持久数据存储非常有用。
在 1.21+ 版本中,Persistent Data 不使用 beans!
以下是 persistentData 的示例:
1.21.1+
1.20.4
1.20.1 - 1.19.2
这些是可在像 persistentData 这样的 NBT 复合标签上使用的方法。
在下面的代码片段中,compound 将指代复合标签。
compound.put(name, tag)
name: 要放入的键名。tag: 要插入的 NBT 标签。普通数字和字符串也可以插入,会自动包装成 NBT 标签。请注意,JS 数字是双精度浮点数!compound[name] = tag bean。compound.get(name)
name: 要获取的键名。const tag = compound[name] bean。| 数据类型 | 设置方法 | 获取方法 |
|---|---|---|
| Boolean | compound.putBoolean(name, value) | compound.getBoolean(name) |
| Byte | compound.putByte(name, value) | compound.getByte(name) |
| Byte array | compound['putByteArray(java.lang.String,byte[])'](name, value) | compound.getByteArray(name) |
| Double | compound.putDouble(name, value) | compound.getDouble(name) |
| Float | compound.putFloat(name, value) | compound.getFloat(name) |
| Integer | compound.putInt(name, value) | compound.getInt(name) |
| Integer array | compound['putIntArray(java.lang.String,int[])'](name, value) | compound.getIntArray(name) |
| Long | compound.putLong(name, value) | compound.getLong(name) |
| Long array | compound['putLongArray(java.lang.String,long[])'](name, value) | compound.getLongArray(name) |
| Short | compound.putShort(name, value) | compound.getShort(name) |
| String | compound.putString(name, value) | compound.getString(name) |
| UUID | compound.putUUID(name, value) | compound.getUUID(name) |
name: 要获取/放入的键名。value: 适当类型的值。如果需要,会进行类型转换。如果尝试读取与实际存储在该键处的类型不同的类型,如果可能,返回值将被转换为适当的类型。
成功的转换:
失败的转换:
compound.getAllKeys()
compound.remove(name)
name: 要从标签中移除的键名。compound.getAsString()
compound.toString()
compound.merge(otherCompound)
otherCompound: 另一个 NBT 复合标签。compound.copy()
compound.isEmpty()
true,否则返回 false。compound.empty。compound.size()
compound.sizeInBytes()