基本的には2通りあります。
1)ちょうどこの
var pauseButton: PauseButton!
などのようdidMoveToViewでそれをインスタンス化よりのようなプロパティを作成します。
override func didMoveToView(view: SKView) {
pauseButton = PauseButton(theTexture: pauseButtonTexture,gameScene: self)
addChild(pauseButton)
}
2)最初にやろうとしたことを実行できるように、遅延インスタンス化を使用します。最も単純な形で
で怠惰varがあなたも、すべて同じ場所にこのボタンの多くのプロパティを追加するので、同じようにそれを行うことができますが、1
lazy var pauseButton: PauseButton = PauseButton(theTexture: pauseButtonTexture,gameScene: self)
override func didMoveToView(view: SKView) {
ステップを実行せずに自己を使用することができます。
lazy var pauseButton: PauseButton = {
let button = PauseButton(theTexture: pauseButtonTexture,gameScene: self)
button.zPosition = 200
button.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
button.alpha = 0.5
return button
}()
override func didMoveToView(view: SKView) {
addChild(pauseButton)
}
すべてのSKNode/SKSpriteNodeなどにはシーンプロパティがあることを覚えておいてください。あなたのボタンクラスがSKNode/SKSpriteNodeのサブクラスである場合、シーンプロパティを取得して、 "as"演算子を使用して初期化メソッドでシーンを渡さずにGameSceneへの参照を取得できます。先端として、例えば
class GameScene: SKScene {
lazy var pauseButton: PauseButton = PauseButton(theTexture: pauseButtonTexture,gameScene: self)
var someBool = false
override func didMoveToView(view: SKView) {
addChild(pauseButton)
pauseButton.loadPausedLabel()
}
func someMethod() {
}
}
class PauseButton: SKSpriteNode {
func loadPauseLabel() {
// Way 1, reference to current scene but not to specific class
guard let scene = scene else { return }
// Scene property is optional and is nil until button is added to a Scene so add the guard check.
scene.someBool = true // NOT WORKING
scene.someMethod() // NOT WORKING
let label = SKLabelNode(...
scene.addChild(label) // WORKING
// Way 2, use "as" to cast to specific scene (e.g GameScene) so you can call properties/methods on it. This is the same as passing GameScene in the init method.
guard let gameScene = scene as? GameScene else { return }
// Scene property is optional and is nil until button is added to a Scene so add the guard check.
// The button must be added to the scene you are trying the as? cast with, in this example GameScene.
gameScene.someBool = true // WORKING
gameScene.someMethod() // WORKING
let label = SKLabelNode(...
gameScene.addChild(label) // WORKING
}
}
、私はpauseButtonサブクラスで一時停止ラベルを追加しないだろう、私はシーンも自己内から、または一時停止のメニューサブクラスからそれを追加します。 また、私は各ボタンをサブクラス化しないでしょう、私はあなたのゲームのすべてのボタンのために使用することができる1クラスを作成します。ボタン名を持つ列挙型を作成し、それを押されたときにボタンを区別するためにinitメソッドに渡すことができます。
ボタンのサブクラスは、アニメーション、テクスチャなどを処理するだけです。リンゴのゲームDemoBotsを例にチェックアウトすることができます。
希望します。
GameSceneメソッドからGameSceneを渡す場合は、「self」を使用してください。 –
@phillipMills引数型は何ですか?? GameScene内で 'didMoveToView'の前に' let pauseButton = PauseButton(theTexture:pauseButtonTexture、gameScene:self) 'を呼び出すとエラー' 'NSobject - >() - > GameSceneを期待される引数型GameScene'に変換できません。 initは次のようになります: 'init(theTexture:SKTexture、gameScene:GameScene){'ありがとう! – Sam
あなたはGameSceneメソッドの中でそれを呼んでいないと言っているようです。 –