Steven Thiel Steven Thiel - 6 months ago 19
Swift Question

Calling function defined in GameScene from an NSTimer in GameViewController

In my GameViewController.swift I have a function called resumeGameScene. In that function I start 3 timers. All of which call 3 separate functions (lane1,lane2, and lane3) in my GameScene.swift file. I've tried the making my functions class functions but this didn't work because I have more functions and variables inside these functions (lane1, lane2, and lane3).

GameViewController.swift:

func resumeGameScene() {
if (GameScene.unarchiveFromFile("GameScene") as? GameScene) != nil
{
let skView = self.view as! SKView

if skView.scene != nil
{
skView.paused = false

if resumeTime1 != nil && resumeTime2 != nil && resumeTime3 != nil
{

timer1 = NSTimer.scheduledTimerWithTimeInterval(resumeTime1!, target: self, selector: #selector(GameScene.lane1), userInfo: nil, repeats: false)

timer2 = NSTimer.scheduledTimerWithTimeInterval(resumeTime2!, target: self, selector: #selector(GameScene.lane2), userInfo: nil, repeats: false)

timer3 = NSTimer.scheduledTimerWithTimeInterval(resumeTime3!, target: self, selector: #selector(GameScene.lane3), userInfo: nil, repeats: false)



}

}
}
}


GameScene.swift:

func lane1()
{


let randomNum = arc4random_uniform(100) + 1

levels()

if randomNum < 46
{
mouseFire(1, laneFire: fire)

}
else
{
enemyFire(1, laneFire: fire)

}

}//End of lane1 func


func lane2()
{

let randomNum = arc4random_uniform(100) + 1

levels()

if randomNum < 46
{
mouseFire(3, laneFire: fire)

}
else
{
enemyFire(3, laneFire: fire)

}

}//End of Lane2 func


func lane3()
{


let randomNum = arc4random_uniform(100) + 1

levels()

if randomNum < 46
{
mouseFire(5, laneFire: fire)

}
else
{
enemyFire(5, laneFire: fire)

}

}//End of Lane3 func

Answer

Your target is self hence selector will be invoked on self which is GameViewController. Since your selector is not in GameViewController thus this will not work. You need to create object of GameScene and pass it to target.