Andres Leal Andres Leal - 2 years ago 120
Swift Question

Change users character

I am trying to change the users characters in sprite kit.

I have two views, one with the Play view (the actual game) and the other view to choose a character.

I want the user to choose a character from the character view so in the play view he/she can play with the character selected before.

So I have tried to use NSUserDefaults to save a number depending on the character like this:

if self.nodeAtPoint(location) == self.poolBanner {
//change to pool ball
userDefaults.setInteger(1, forKey: "PBChange")
print("Pool Ball selected")
if self.nodeAtPoint(location) == self.tumbleweedBanner {
//change the character to tumbleweed
userDefaults.setInteger(2, forKey: "TWChange")
print("Tumbleweed Ball selected")

This code is from the character view, when the player select the character they want to use

Now this code is from the play view:

if TWNumber == 2{
hero.texture = SKTexture(imageNamed: "Tumbleweed")
hero.size = CGSize(width: 60, height: 57)
else if PBNumber == 1 {
hero.texture = SKTexture(imageNamed: "PoolBall")
hero.size = CGSize(width: 60, height: 60)

When I tap on to change the character it stays on the same character I have choosed. If I select the poolBall it change the first time and then change it to the tumbleweedBall It will stay the same.

I think that the image are overriding themselves, but I don't know how to ignore the last image if the new is selected...

Answer Source


  1. User chooses their character and this code is called:

    //Enum of possible characters, with their sprite texture names too.
    enum GameCharacter: String {
        case Tumbleweed = "Tumbleweed"
        case PoolBall = "PoolBall"
    func characterSelect(type: GameCharacter) {
        let ud = NSUserDefaults.standardUserDefaults()
        //Save the current character in User Defaults
        ud.setObject(type.rawValue, forKey: "Current_Character")
    //When they choose the character:
    characterSelect(.Tumbleweed) //Or Whatever character you have
  2. Game Scene: Load character texture

    func loadCharacter() {
        let ud = NSUserDefaults.standardUserDefaults()
        if let currentCharacter = ud.objectForKey("Current_Character") as? String   {
            hero.texture = SKTexture(imageNamed: currentCharacter)
        } else {
            hero.texture = SKTexture(imageNamed: "Tumbleweed")
    override func viewDidLoad() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download