0

Non-functional code:

 if sprite.texture == "texture" {
 (code)
}

I'm trying to access the texture of the sprite to run code when the sprite has a specific texture. Currently the texture is only in my Assets hence the parentheses. Can anyone figure out how to rewrite this code in a way that will work?

B.Toaster
  • 169
  • 2
  • 13
  • That's not a good design. Use userData with each sprite instead. – El Tomato Jul 31 '17 at 23:09
  • 1
    Possible duplicate of [Getting the filename of an SKSpriteNode in Swift 3](https://stackoverflow.com/questions/41272365/getting-the-filename-of-an-skspritenode-in-swift-3) – Knight0fDragon Aug 01 '17 at 00:35
  • I voted to close due to it answering your question, but in reality, I agree with El Tomato, redesign your approach to solve this problem better – Knight0fDragon Aug 01 '17 at 00:36

1 Answers1

1

sprite.texture is of type SKTexture?, so you can't compare it against a string, but should rather compare against an actual SKTexture object.

Nevertheless, you should try to redesign your code, as suggested by others in the comments on your question. Checking against a texture itself is not good design. For one thing, if you decide to use a different texture for your sprites in 2 months, then you will need to remember to revisit this code.

I would suggest subclassing from SKSpriteNode and checking if a sprite's type is the same as your subclass. Other alterantives are to compare the sprite.name or the sprite's userData.

JohnV
  • 981
  • 2
  • 8
  • 18