user3128464 user3128464 - 5 months ago 14
iOS Question

Detect when parent of node changes

So I have a class that is a subclass of

SKSpriteNode
and I want it to be alerted when its parent changes, or scene if it has no parent node, so that I know the size of its container. I tried doing the following:

class MyNode: SKSpriteNode {

override var parent: SKNode? {
didSet {

//code here

}
}

override var scene: SKScene? {
didSet {

//code here

}
}

}


However, I got the error,
Cannot observe read-only property 'parent'; it can't change
and
Cannot observe read-only property 'scene'; it can't change
, which makes me believe that there are private values somewhere and those properties are calculated. I don't know what else to do besides manually calling a function every time I add my node to something else, but I feel that is an ugly solution. Thanks for any help, and sorry if the solution is obvious; I'm fairly new to SpriteKit.

Answer

You are setting class properties for the detection, which I don't think you will be allowed to change when the class is initialized. I would recommend checking in one of the game loop functions like didFinishUpdate. Then you will be able to check every frame and perform the correct operations.

Comments