我希望通过保存玩家的当前状态来保存游戏进度,例如他在地图上的位置,HP,法术力,当前状态等。
我需要有关如何将播放器对象转换为NSdata并将其存储在NSUserDefaults中的帮助。
我有播放器的以下属性,但如何使用NSCoding对它们进行编码?我是否必须编码每一个属性?以及如何编码组件?
var spriteComponent: SpriteComponent!
var animationComponent: AnimationComponent!
var playerMoveComponent: PlayerMoveComponent!
var healthComponent: HealthComponent!
var playerAttackComponent: PlayerMeleeAttackComponent!
var roundHouseSwingComponent: RoundHouseSwingComponent!
var playerMagicAttackComponent: PlayerMagicAttackComponent!
var attackBodyNode: SKNode!
var dashDistance = GameSettings.playerDashDistance
var agent: GKAgent!
var health: Int!
var fullHealth: Int!
var mana: Int!
var fullMana: Int!
var action: Int!
var fullAction: Int!
var hasGateKey: Bool!
var numberOfPotionCarried: Int!
var playerState: PlayerState!
var movementEnabled: Bool!
var dashAttackActivated: Bool!
感谢您提前提供任何帮助。
答案 0 :(得分:0)
如果组件或实体符合NSCoding(例如SKNode及其子类),则无需对其进行编码。请改用KeyArchiver。
这是示例代码,显示了如何保存和加载数据。
let fileManager = FileManager.default
guard let documentsURL = fileManager.urls(
for: FileManager.SearchPathDirectory.documentDirectory,
in:FileManager.SearchPathDomainMask.userDomainMask).last else {
fatalError("Failed to find the documents folder!")
}
let savedGameURL = documentsURL
.appendingPathComponent("SavedGame.plist")
do {
try data.write(to: savedGameURL)
} catch let error {
print("Error writing: \(error)")
}
var loadedData : Data?
do {
loadedData = try Data(contentsOf: savedGameURL)
} catch let error {
print("Error reading: \(error)")
}
如果有一个自定义类,则可以使其成为NSObject的子类,并符合NSCoding。您需要实现以下方法:init?(编码器:NSCoder)和func encode(带有:NSCoder)。请参阅 https://developer.apple.com/documentation/foundation/nscoding 有关更多信息。
希望这会有所帮助。