I'm trying to make a function that I can call on to update my UILabel's scoreLabel.text
. However, I get an error whenever I try to change it. What's confusing to me is that I don't receive an error when changing it inside viewDidLoad()
. Everywhere else returns the following error:
In the console I also get error:
fatal error: unexpectedly found nil while unwrapping an Optional value.
So what I've been lead to believe is that when calling my function to update the text, the view hasn't loaded the UILabel yet. But I'm certain that this function is called only once the view has loaded.
Things I've checked/tried for:
- That my IBOutlet is properly connected
- That my function is being called
- Using both
scoreLabel.text
andself.scoreLabel.text
- Using a Strong and Weak outlet connection
I am also positive that changeTextLabel
is being called after scoreLabel
is loaded into memory. But again my error seems to say otherwise.
Here's a complete markup of my code. I've removed some irrelevant details for readability:
import UIKit
import SpriteKit
class GameViewController: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//This is where all my other code was
print(scoreLabel.text)
scoreLabel.text = "Testing" //This line can be run
}
func changeTextLabel() {
print("changeTextLabel called")
if self.scoreLabel != nil {
self.scoreLabel.text = "yay"
} else {
print("scoreLabel is nil") //This is called every time
}
}
}
Thanks for your time
Edit:GameScene.swift
This is only the part that should be of concern
func projectileDidCollideWithMonster(projectile: SKSpriteNode, monster: SKSpriteNode) {
print("Hit")
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let object = storyBoard.instantiateViewController(withIdentifier: "GameViewController") as! GameViewController
object.changeTextLabel()
projectile.removeFromParent()
monster.removeFromParent()
}