2

I want to save my game progress by saving the player's current status, such as his position on map, HP, mana, current state, etc..

I need help on how to convert the player object to NSdata and store it in NSUserDefaults.

I have the following properties for player, but how do I encode them using NSCoding? Do I have to encode every single property? and how do I encode components?

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!

Thanks for any help in advance.

Bob
  • 155
  • 1
  • 8

1 Answers1

0

If the components or entities conform to NSCoding (such as SKNode and its subclasses), you don't have to encode them. Please use KeyArchiver instead.

Here is a sample code showing how to save and load data.

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)")
}

If there is a custom class, you can make it to subclass NSObject, and conform to NSCoding. You need to implement to methods: init?(coder: NSCoder) and func encode(with: NSCoder). Please see https://developer.apple.com/documentation/foundation/nscoding for more information.

Hopefully it will help.

Yaming Lin
  • 113
  • 9