简体   繁体   English

Swift SpriteKit委托模式

[英]Swift SpriteKit Delegate Pattern

I have been trying to learn how to use delegates recently and actually seem to understand it for the most part. 我一直在努力学习如何最近使用代表,实际上似乎在很大程度上理解它。 However I have one problem. 但是我有一个问题。

I have 1 GameViewController, 1 StartScene and 1 MenuScene 我有1个GameViewController,1个StartScene和1个MenuScene

In my GameViewController I have 2 methods that I would like to get called from MenuScene. 在我的GameViewController中,我有两个方法,我想从MenuScene调用。 So far I have been using NSNotification, which works fine but I am trying to use delegates. 到目前为止,我一直在使用NSNotification,它工作正常但我正在尝试使用委托。

So I have set up a protocol in MenuScene 所以我在MenuScene中设置了一个协议

 protocol MenuSceneDelegate {
 func gameOver()
 func showGameCenter()
}

I than referenced it like so 我比这样引用它

 var menuSceneDelegate: MenuSceneDelegate?

In GameViewController I added the MenuSceneDelegate at the top. 在GameViewController中,我在顶部添加了MenuSceneDelegate。 All is very standard so far. 到目前为止,一切都很标准。 However the main problem I have is that when I set the delegate in GameViewController like so 但是我遇到的主要问题是当我在GameViewController中设置委托时就像这样

 let skView = view as! SKView!
    var scene = StartScene(size: skView.bounds.size)

    skView.ignoresSiblingOrder = true
    scene.scaleMode = .ResizeFill

    skView.presentScene(scene)

    scene.menuSceneDelegate = self   //Sets delegate to StartScene not MenuScene

it only applies to the StartScene. 它只适用于StartScene。 How can I set the GameViewController delegate from StartScene to MenuScene. 如何将GameViewController委托从StartScene设置为MenuScene。 Everything works fine if I would first present the MenuScene. 如果我首先展示MenuScene,一切正常。 However I present StartScene first and therefore I am trying to understand how I set the delegate to MenuScene. 但是我首先介绍了StartScene,因此我试图了解如何将委托设置为MenuScene。

I tried something like this below but it doesnt work and just doesnt seem right 我试过下面这样的东西,但它不起作用,只是似乎没有

 var menuScene = MenuScene(size: skView.bounds.size)
 menuScene.menuSceneDelegate = self

I would appreciate any help or support. 我将不胜感激任何帮助或支持。 Thank you very much 非常感谢你

基本上解决方案是在我从开始场景变为游戏场景时设置委托,而不是在开始时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM