Sprite kit 必需的init?(编码器aDecoder:NSCoder){fatalError(";init(编码器:)尚未实现";)}
您好,在Spritekit中,我的代码失败,因为GKPomponent强制我实现: a。我不需要一个“required init”。 B在运行时,它调用这个函数而不是我的普通init(),并失败。 Cinit(coder:aDecoder)不能解决我调用它的问题 问题:调用我的init而不是强制要求的init的解决方案 在其他答案中,建议使用super.init(coder:aDecoder)的解决方案,但它并没有解决我不调用它的问题Sprite kit 必需的init?(编码器aDecoder:NSCoder){fatalError(";init(编码器:)尚未实现";)},sprite-kit,Sprite Kit,您好,在Spritekit中,我的代码失败,因为GKPomponent强制我实现: a。我不需要一个“required init”。 B在运行时,它调用这个函数而不是我的普通init(),并失败。 Cinit(coder:aDecoder)不能解决我调用它的问题 问题:调用我的init而不是强制要求的init的解决方案 在其他答案中,建议使用super.init(coder:aDecoder)的解决方案,但它并没有解决我不调用它的问题 required init?(coder aDecoder:
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//这段代码应该在sprite下添加一个简单的eplipse,通过使其成为GKComponent并将其添加到GKEntity来产生//阴影效果
import Foundation
import GameplayKit
import SpriteKit
//GKEntity to add GKComponents
class Entity: GKEntity{
//A variable that is a GKComponent defined as ShadowComponent: GKComponent
var shadow: ShadowComponent
//My init
override init() {
shadow = ShadowComponent(size: CGSize(width: 50, height: 50), offset: CGPoint(x: 0, y: -20))
super.init()
addComponent(shadow)
}
//Forced by compiler to have it
**required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}**
}
系统需要所需的init;当系统自动加载组件时,将调用它。以界面生成器为例。您可以查看更多信息。实体是否已添加到场景编辑器中 因此,您需要关注实体的创建方式。如果要调用自定义init,则需要以编程方式初始化它 如果您希望继续在场景编辑器中使用实体,我可以建议使所需的init工作:
required init?(coder aDecoder: NSCoder) {
shadow = ShadowComponent(size: CGSize(width: 50, height: 50), offset: CGPoint(x: 0, y: -20))
super.init(coder: aDecoder)
addComponent(shadow)
}
在初始化之前,所有变量都需要分配一个值。由于您的shadow没有值,编译器将强制您重写必需的init,以便您可以为shadow指定一个值 要解决此问题,只需将阴影设置为懒惰:
lazy var shadow =
{
[unowned self] in
let shadow = ShadowComponent(size: CGSize(width: 50, height: 50), offset: CGPoint(x: 0, y: -20))
addComponent(shadow)
return shadow
}()
然后,第一次使用阴影时,它将为您创建和添加组件
我们需要让它变懒的唯一原因是它的addComponent方面。您的代码可以这样编写,以避免必须使用惰性组件,但您需要调用函数来添加组件
let shadow = ShadowComponent(size: CGSize(width: 50, height: 50), offset: CGPoint(x: 0, y: -20))
func addComponents(){
addComponent(shadow)
}