0

How would I call the sun object I have made in a function (hello) from another function (collide)?

func collide() {
        if (CGRectIntersectsRect(player.frame, **sun.frame**)) {
            [EndGame];
        }

 func hello() {
        let sun = SKSpriteNode(imageNamed: "Sun")
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
bandoy123
  • 253
  • 4
  • 12

2 Answers2

4

You can't - the sun variable is local to the hello function, and it doesn't exist outside its scope.

If collide is invoked from hello, you can just pass it as an argument:

func collide(sun: SKSpriteNode) {
    if (CGRectIntersectsRect(player.frame, sun.frame)) {
        [EndGame];
    }
}

func hello() {
    let sun = SKSpriteNode(imageNamed: "Sun")
    ...
    collide(sun)
}

Otherwise if, as I think, these are instance methods of a class, just turn the sun variable into an instance property:

class Test {
    private var sun: SKSpriteNode?

    func collide(sun: SKSpriteNode) {
        if let sun = self.sun {
            if (CGRectIntersectsRect(player.frame, sun.frame)) {
                [EndGame];
            }
        }
    }

    func hello() {
        self.sun = SKSpriteNode(imageNamed: "Sun")
    }
}
Antonio
  • 71,651
  • 11
  • 148
  • 165
1

In addition to Antonio's answer, you can search an SKNode's children using a unique name.

For example.

let sun = SKSpriteNode(imageNamed:"Sun")
sun.name = "sun"
self.addChild(sun)

You can get it back by

if let sun =  self.childNodeWithName("sun")
{
    //use sun here
}

childNodeWithName returns an optional SKNode?.

rakeshbs
  • 24,392
  • 7
  • 73
  • 63