ios - 无法将 SKNode 转换为 SKNode 的子类

标签 ios swift sprite-kit sknode

我从一个函数返回一个 SKNode,我需要将它转换为自定义 SKNode。我收到错误消息无法将 SKNode的值分配给类型GroundNode。如果我强制转换,它会编译,但在运行时失败。我错过了什么?

// Custom node class
class GroundNode: SKNode {
        weak var entity: GKEntity!
    }

// Return node function
func returnNode() -> SKNode {
    ...
    return node
}

// Where I am getting the error
func setupNode() {
    var ground: GroundNode
    ground = returnNode() // error here.
    //// ground = returnNode() as! GroundNode fails at runtime.
}

编辑:我从 sks 文件中获取了一个 SKNode。我的 returnNode() 只是获取带有名称的子节点,并将其返回到我的 setupNode() 函数。我需要添加实体属性,所以我想将返回的 SKNode 转换为 GroundNode 类型。

我看过this计算器帖子。

这适用于 SKSpiteNode,但显然不适用于 SKNode,这对我来说意义不大。

如果我将 SKNode 从我的 sks 文件转换为 GroundNode,它会在运行时崩溃。

最佳答案

根据您的代码:

// Custom node class
class GroundNode: SKNode {
    weak var entity: GKEntity! = GKEntity() // or some custom initialization...
}

// Where I am getting the error
func setupNode() {
   var ground: GroundNode
   ground = returnNode() as? GroundNode
}

发生这种情况是因为 returnNode 输出是一个通用的 SKNode,您必须将您的转换显式转换为子类化的 GroundNode。

编辑: 好的,通过你的更新我想我已经理解你的问题了,你忘记了为你的 GroundNode 设置自定义类:

enter image description here

关于ios - 无法将 SKNode 转换为 SKNode 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37460222/

相关文章:

ios - 带有 UITextField : Trouble with Delegates and Dequequing 的自定义 Xib UITableViewCell

iphone - 如何将其中包含HTML标记的字符串显示为纯文本

ios - UILabel 仅在放置在 viewcontroller 的 viewDidAppear 中时显示

objective-c - 使用 SpriteKit 的 TextureAtlas 并通过 Xcode 命令行构建时,iOS 应用程序崩溃

ios - SpriteKit 中火箭的烟雾效果

ios - 根据物体的速度和旋转找到所需的点

ios - 什么应该在 View Controller 中,什么应该在 View 中?

swift - if 语句和其他语句中的变量上有感叹号前缀吗?

swift - 匹配元组范围内的整数元组

swift - 是否可以在 Swift 中创建具有 Self 或关联类型要求的通用计算属性,如果可以,如何创建?