Swift 无法强制转换类型为';SKSpriteNode';到myApp.CustomSprite

Swift 无法强制转换类型为';SKSpriteNode';到myApp.CustomSprite,swift,sprite-kit,Swift,Sprite Kit,我是Swift和SpriteKit的新手,所以请容忍我。 我正在尝试创建一个简单的游戏,我创建了一个自定义类(CustomSprite): CustomSprite使用spriteColor仅用于检查原因(游戏后期) 我正在尝试在游戏场景中制作一个新的精灵: var mPlayer: CustomSprite = CustomSprite() override func didMove(to view: SKView) { //crashes here (mPlayer = self

我是Swift和SpriteKit的新手,所以请容忍我。 我正在尝试创建一个简单的游戏,我创建了一个自定义类(CustomSprite):

CustomSprite使用spriteColor仅用于检查原因(游戏后期) 我正在尝试在游戏场景中制作一个新的精灵:

var mPlayer: CustomSprite = CustomSprite()

override func didMove(to view: SKView) {

    //crashes here (mPlayer = self. xxxxxx)
    mPlayer = self.childNode(withName: "mainPlayer") as! CustomSprite
    mPlayer.spriteColor = "red"
}
我在运行游戏并开始移动时出现以下错误:

Could not cast value of type 'SKSpriteNode' to 'myApp.CustomSprite'
我不明白我必须做什么来修复它,以及为什么会发生这种情况。
我确实将
.sks
文件中的自定义类设置为CustomSprite并保存,但它没有更改或修复错误。

您可以尝试用可选绑定替换代码:

if let sprite = self.childNode(withName: "//mainPlayer") as? CustomSprite {
           mPlayer = sprite
           // do whatever you want with your mPlayer
}

mainPlayer
之前的“/”指定搜索应从根节点开始,并在整个节点树中递归执行。否则,它将从当前位置执行递归搜索。您可以找到更多详细信息

此解决方案不起作用,仍然会遇到相同的问题。谢谢。你确定你已经正确地将你的与主播放器相关的自定义类型设置到你的SKS文件(文件检查器)了吗?是的,我有同样的代码(使用SKSpriteNode,而不是CustomSprite),唯一的区别是我现在正在尝试对SKSpriteNode进行子类化,这样我就可以在SKSpriteNode(spriteColor)中有另一个值。尝试将断点设置为行mPlayer=sprite和debugConsole类型:po sprite。如果结果为零,您的主要玩家不在游戏场景中。欢迎,有时重新启动是一个很好的方法,使事情变得更好、更强大。祝你好运
if let sprite = self.childNode(withName: "//mainPlayer") as? CustomSprite {
           mPlayer = sprite
           // do whatever you want with your mPlayer
}