Unable to subclass SKSpriteNode

An attempt by the SKSpriteNode subclass to make my game code cleaner, and I obviously donโ€™t understand anything. Here is a very simple example: I create a new Swift file called Alien.swift with the following contents:

 import SpriteKit class Alien: SKSpriteNode { } 

In my game, I:

  let alienSprite: Alien = Alien() print("It an \(alienSprite)") 

and I get:

This is the name (SKSpriteNode): '(null) ...'

Even Xcode says it is "aliensSprite":

enter image description here

Why doesn't it print at run time that it is "alienSprite"?

Edit: including one of my comments here - I really collect the sprite from my .sks file, where I put it in the scene editor and set its own class. I'm trying to pick it up:

 let alien = childNodeWithName("alien") as! alienSprite 

but I get the error:

 Cannot cast SKSpriteNode to alientSprite 
+5
source share
3 answers

Pay attention to the state of the scene file. If you see it shaded, it means that it has not yet been saved. If you compile your code while working in the scene editor, saving will not happen, so be sure to delete cmd + s to save it before compilation. enter image description here

Now, if people are trying to understand why class names are not saved, make sure you press ENTER or leave the text field and switch to another text field to ensure that the class name is saved, otherwise it will return to an earlier state.

enter image description here

+2
source

You are not using a variable name

When you announce

  let alienSprite: Alien = Alien() 

Basically you create an empty SKSpriteNode. This means that when you perform line interpolation, you print the actual SKSpriteNode and its properties.

To fix this, you have two options.

Original

  • Print the alienSprite type:

     print("It an \(type(of: alienSprite))") 
  • Name the Alien and type in:

     alienSprite.name = "Alien" print("It an \(alienSprite.name)") 

10/25/16

If you want something like @ Knight0fDragon, you can do the following:

 print("It an \(type(of: alienSprite)) \(alienSprite)") 

This is basically adding my original answer.

+2
source

When you print an object, as in print("It an \(alienSprite)") , you simply request its description property. By default for SKNode this property simply prints the name property of the object, since you did not override this behavior, you received the message (SKSpriteNode) name: null . If you want to override it, change the description in your new class to something more convenient, something like this should work:

 class Alien : SKSpriteNode { override var description: String { return "\(String(describing: type(of:self)))" } } 

debugDescription that you also have a similar debugDescription to control what is printed by the debugger.

+1
source

Source: https://habr.com/ru/post/1258429/


All Articles