简体   繁体   中英

Getters on spritekit

I have a little problem. Let me introduce it to you: On SpriteKit, we have MyScene.m and .h file. This class have a property called "size". We can access it from the MyScene.m file by using "self.size". I've created a class called Menu, so we have a .m and a .h. This class is a subclass of "SKNode". My problem is that I want to get the value of "size" property of MyScene class in my Menu class. Because I have some nodes which I will add to Menu object, and their position will depend on MyScene "size" property.

Can you please tell me how to do it. thank you

You can use scene property of SKNode to retrieve the scene that contains the node. For more info see SKNode Class Reference .

You could use an initWithSceneSize:(CGSize)size method for your Menu class and then store the size in a ivar or property of your Menu class.

Example with a ivar in your .m :

@implementation MenuClass
{
    CGSize sceneSize;
}

-(instancetype)initWithSceneSize:(CGSize)size
{
     sceneSize = size;
     if (self = [super init])
     {
         // do whatever
     }
     return self;
}

Now you can use the sceneSize ivar wherever you want in that class for sizing and/or alignment of elements.

Another option is detailed in the other answer , which is using the scene property of SKNode .

That is a viable option but be aware that if the node is not currently a child of the node tree, the scene property will be nil . So you should make sure that it is currently added to the scene's node tree.

An example would be that if you tried to use the scene property in your constructor, it would not be accessible at that point and you'll be baffled.

Definitely a viable option and a good one, but just be aware of that aspect or that might be your next question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM