简体   繁体   English

Swift 4.2-类型'(____)->()->(____)'的值没有成员'childNode'

[英]Swift 4.2 - Value of type '(____) -> () -> (____)' has no member 'childNode'

I created a custom class in swift to manage my main menu for a game I'm making I linked it to the SKScene file and tried to create a constant to access the variable and I got this error: Cannot use instance member 'childNode' within property initializer. 我迅速创建了一个自定义类来管理我正在制作的游戏的主菜单,并将其链接到SKScene文件,并尝试创建一个常量来访问变量,但出现此错误:无法在实例中使用实例成员'childNode'属性初始化器。

import SpriteKit
import GameplayKit

class MainMenu: SKScene {

    let startGameButton:SKSpriteNode = self.childNode(withName: "SpriteName")

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    }
}

Does anyone know whats happening? 有人知道发生了什么吗? If not is there another way to access sprites. 如果没有,还有另一种方法可以访问精灵。

Initial values for let variables must be constants that can be initialized before the init() method is executed. let变量的初始值必须是可以在执行init()方法之前初始化的常量。 That in turn means they can't reference self . 这意味着他们无法引用self

One workaround for that is making them lazy instance variables, which get initialized when they are first used (which, by definition, can't happen before init() has returned a reference to the object). 一种解决方法是使它们成为lazy实例变量,这些变量在首次使用时会被初始化(根据定义,在init()返回对该对象的引用之前不可能发生这种情况)。 In that case, the lazy variable would be initialized with the result from a closure. 在这种情况下,惰性变量将使用闭包的结果进行初始化。

Change: 更改:

let startGameButton:SKSpriteNode = self.childNode(withName: "SpriteName")

to

lazy var startGameButton:SKSpriteNode = self.childNode(withName: "SpriteName") as! SKSpriteNode

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

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