So basically I am trying to have this app change its background when a button is pushed. The way I'm trying to do it is to set a variable 0 and if the button is pushed it will either make it 1 less or 1 more. Currently, the background does change if I manually change the variable in the class but it does not change when I tried to use the buttons.
This is my code for my changing the background ///////////////////////////////////////////////////
let gameVC = SelectCharViewController()
override func didMove(to view: SKView) {
let backgroundCheck2 = gameVC.getter()
physicsWorld.contactDelegate = self
// var backgroundImage = SKSpriteNode(imageNamed: "background")
if(backgroundCheck2 == 0){
let backgroundImage = SKSpriteNode(imageNamed: "background")
backgroundImage.size = CGSize(width: frame.size.width, height: frame.size.height)
backgroundImage.position = CGPoint(x: frame.midX, y: frame.midY)
backgroundImage.zPosition = -1
addChild(backgroundImage)
}
else{
let backgroundImage = SKSpriteNode(imageNamed: "background2")
backgroundImage.size = CGSize(width: frame.size.width, height: frame.size.height)
backgroundImage.position = CGPoint(x: frame.midX, y: frame.midY)
backgroundImage.zPosition = -1
addChild(backgroundImage)
}
And this is my code for the buttons
import UIKit
class SelectCharViewController: UIViewController {
public var backgroundCheck = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func nightShift(_sender: UIButton){
print(backgroundCheck)
self.backgroundCheck+=1;
print(backgroundCheck)
}
@IBAction func dayShift(_sender: UIButton){
print(backgroundCheck)
self.backgroundCheck-=1;
print(backgroundCheck)
}
func getter() -> Int{
return self.backgroundCheck
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
There are probably a number of things you could be doing differently (using a boolean instead of an integer, for example).
But I suspect that you aren't seeing the desired behavior because your image-changing code is located in
didMove(to:), which is only called when the scene is first presented.To make it work on button press, you could move that code to your own function, like this:
Then, call
changeBackground(backgroundCheck2:)from your button logic, wherever that may be.You'll need a single instance of your scene. Something like this:
So, in this case, you'd call your function like this: