R. Rincón
R. Rincón

Reputation: 361

How to access the value of a variable of a specific instance of GameViewController in Swift

Here's my relevant code:

from my GameScene class:

    func resetCircleAndScore(scale: CGFloat)
{
    circleIsStationary = true
    currScore = 0
    CIRCLE.speed = 1
    CIRCLE.physicsBody!.velocity = CGVector(dx: 0,dy: 0)
    CIRCLE.position = CGPointMake(midX, midY)
    circleScale = scale
    circleSpeed = CONSTSPEED
    CIRCLE.setScale(circleScale)
    currScoreLabel.text = "SCORE: " + Int(currScore).description
    //need to update modeSelected here
}

from my GameViewController class:

public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    modeCopy = modes[row]

    println(modeCopy)
}

I tried to add a getter for modeCopy, as follows:

public func getMode() -> String
{
    return modeCopy
}

The problem is that when I try to call this function from another class, it needs a parameter called "self" of type GameViewController. What I really want to do is access the instance of GameViewController that created my GameScene. I could also access the instance of GameScene the GameViewController created, but I'm not sure how to do that. My ViewDidLoad in GameViewController is below.

override public func viewDidLoad()
{
    self.pickerView.dataSource = self
    self.pickerView.delegate = self

    println("got to beginning of viewDidLoad")
    super.viewDidLoad()

    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene
    {
        // Configure the view.
        let skView = self.view as SKView
        let showStats: Bool = true
        skView.showsFPS = showStats
        skView.showsNodeCount = showStats

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }
}

Upvotes: 1

Views: 303

Answers (1)

Abdullah
Abdullah

Reputation: 7233

If GameScene is your own class you could add one optional parameter of type GameViewController.

class GameScene {
    weak var parentController: GameViewController?

....
}

In viewDidLoad() method when you unarchive GameView do this

scene.parentController = self

Now you could use it in the GameScene

Upvotes: 1

Related Questions