How to store user data in game? (swift, spritekit)

落花浮王杯 提交于 2019-12-11 05:18:31

问题


Let's say I had a game where in the beginning the user gets to choose a couple of things like name, gender, etc, and that will affect a lot of aspects in the game such as the sprite used to render the user, and the text that is displayed.

So every time I leave one area of the game and enter a new one I should figure out according to the user data - what sprite to use and what text to prep. Should I make a separate class with a dictionary just for the user's data and then just call it whenever I enter a new area? Thanks yall.


回答1:


There is a few ways to do this.

I prefer to use a singleton GameData class with NSCoding to house all the properties (arrays, dictionaries etc) that need to be saved permanently.

I like it this way because it makes code more readable and also has the advantage that you can access the properties from anywhere in your project. This way it's also easy to include icloud key value storage.

You can read these 2 questions I answered for a simple example of how this can look

SpriteKit: Why does it wait one round for the score to update? (Swift)

Is there a better way to save a custom class to NSUserDefaults than encoding and decoding everything with NSCoder?

There is a also few good tutorials around such as this

https://www.hackingwithswift.com/read/12/3/fixing-project-10-nscoding

To securely save data you can/should use keychain. To read more about it check out this question.

How secure is NSUserDefaults on iOS 8,9?



来源:https://stackoverflow.com/questions/36725052/how-to-store-user-data-in-game-swift-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!