JustMe
JustMe

Reputation: 316

Access sprite node by its name

I am currently building an iOS game using Objective-C in SpriteKit.

Each asteroid gets an identifier when they are spawned, using this code:

[self.asteroid setName:[NSString stringWithFormat:@"asteroid-%i", self.asteroidCounter]];

Now, I want to be able to remove specific asteroids from the parent based on their integer name. I tried this code, but it was seen as an error:

[self.asteroid withName:[NSString stringWithFormat:@"asteroid-%i", self.asteroidCounter] removeFromParent];

Is there a proper way to achieve this effect?

Thanks in advance!

PS: here is an image of the faulty code in Xcode, if it helps

Upvotes: 0

Views: 78

Answers (2)

MaxKargin
MaxKargin

Reputation: 1545

If you are accessing through properties:

[[self.asteroid withName:[NSString stringWithFormat:@"asteroid-%i", self.asteroidCounter]] removeFromParent];

If asteroid is a child of self, you could also say (this would be the sprite-kit way to do it):

[[self childNodeWithName:[NSString stringWithFormat:@"asteroid-%i", self.asteroidCounter]] removeFromParent];

This is assuming that your property asteroidCounter returns the right value.

Upvotes: 1

Nathan Hillyer
Nathan Hillyer

Reputation: 1979

You're missing some brackets:

[[self.asteroid withName:[NSString stringWithFormat:@"asteroid-%i", self.asteroidCounter]] removeFromParent];

Upvotes: 1

Related Questions