【问题标题】:Can't get Custom Class working in SpriteKit Scene (swift & xcode7 beta)无法让自定义类在 SpriteKit 场景中工作(swift & xcode7 beta)
【发布时间】:2015-06-14 18:46:51
【问题描述】:

我不确定这是否是一个错误,但即使我在其中一个 Sprite 上设置了自定义类名称,它似乎也被完全忽略了。

我尝试使用拖动的资产,然后使用空节点,两者都完全忽略了 Monkey 类关联,只是创建了一个原始的 SKSpriteNode。

Monkey 节点代码如下。

import Foundation
import SpriteKit

class Monkey: SKSpriteNode{

    let monkeyWalkAtlas = SKTextureAtlas(named: "MonkeyWalk")

    override init(texture: SKTexture?, color: NSColor, size: CGSize) {
        super.init(texture: texture, color: color, size: size)
        print("Monkey.init debug")
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

注意:.sks 节点上的自定义类是 xcode7 中的新类。

2015 年 6 月 21 日编辑

我简化了设置,但在 iOS9 模拟器中编译/运行时仍然存在问题。我使用默认 SpriteKit 模板创建了一个项目,将 GameSence 更改为仅具有以下内容(以及空的 Monkey 类)

import SpriteKit

class GameScene: SKScene {

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("touch down")
       /* Called when a touch begins */
        for node in self.children {
            print(node)
        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

public class Monkey: SKSpriteNode {}

在 GameScene.sks 上拖了一个 Empty 节点,将自定义类设置为 Monkey,但是当我触摸打印子节点时,我又得到了:

touch down
<SKSpriteNode> name:'SKNode_0' texture:['nil'] position:{753.5, 333.5} scale:{1.00, 1.00} size:{0, 0} anchor:{0, 0} rotation:0.00

【问题讨论】:

  • 我担心这可能不适用于 Swift 命名空间的类名。您是否尝试过使用 ObjC 类(或名称为 @objc(name) 的 Swift 类)?无论哪种方式,它都可能值得filing a bug
  • 还没有升级到xcode7,但可能是你还没有实现init(coder:)方法。据推测,您在 Xcode 构建器中修改的任何内容都将使用 coder init 方法来完成它的工作,因此如果您还没有实现它,它将无法使用它。
  • 你做了,但它不会返回一个可用的对象。如果 Xcode 使用编码器来保存对象然后重新加载它,您的对象将无法参与,因为它的 fatalErrors() 是它的出路。
  • 很抱歉听到这不能解决您的问题。不过,您对 init(coder:) 进行了“正确”实现可能是件好事。即使其他原因导致您的问题,可能仍然需要正确实现 init(coder:)。
  • 我无法复制;我创建了一个空的class Monkey: SKSpriteNode {},创建了一个场景,添加了一个空节点,将其链接起来,然后使用以下代码对其进行实例化:let c = SKScene(fileNamed: "MyScene")!; print(c.children.first! as! Monkey)。这没有崩溃。您是否尝试过清理项目?创建一个新场景,班级?请记住在尝试链接之前先创建类。 Xcode 需要一个现有的类才能成功链接。

标签: xcode swift sprite-kit swift2 xcode7


【解决方案1】:

在 Swift 中,您总是必须在类名之前添加模块名。您可以在“产品模块名称”字段的构建设置中找到模块名称。 如果您在项目名称中使用“-”,则模块名称会将“-”转换为“_”。(在我的名为“Test-Game”的测试项目中,模块名称为“Test_Game”,所以我必须使用“Test_Game.Monkey”作为自定义类,在当前 Xcode Beta 中适用于我)

【讨论】:

  • 这对我有用!请务必将模块名称检查为空格,并且某些字符将按照上面的建议使用“-”和“_”进行更改。
【解决方案2】:

对于使用较新版本的 XCode 遇到此问题的任何人:@Nightmare_82 的解决方案是正确的,但产品模块名称不再是可用的设置。更高版本的 XCode 使用产品名称作为模块名称。我的产品名称设置为“我的应用程序(开发)”的开发版本,我将其切换为“我的应用程序开发”,一切都很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2011-05-22
    相关资源
    最近更新 更多