Cannot assign value of type '[SKNode]' to type 'SKSpriteNode!'

二次信任 提交于 2019-12-12 05:28:23

问题


I'm writing a Galaga-style game in Swift 3 with SpriteKit and I keep getting an error that says

Cannot assign value of type '[SKNode]' to type 'SKSpriteNode!'

Can anyone explain what this means so that I can fix it myself in the future and also give me a possible solution?

Here's the function where I get the error:

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

    for touch in touches {
        let location = (touch as UITouch).location(in: self)
        if fireButton = self.nodes(at: location) {
            shoot()
        } else {
            let touchLocation = touch.location(in: self)
            spaceship.position.x = touchLocation.x
        }
    }
}

I get the error on the line with if fireButton = self.nodes(at: location)


回答1:


The function self.nodes(at: location) returns an array of all SKNodes that intersect location. The error occurs because you are trying to assign the whole array of SKNodes (i.e. [SKNode]) to a variable that references only a single node.

Also note that since self.nodes(at: location) returns all the nodes that intersect the specific location, you will need to iterate through the array of nodes to find the node you are looking for.

To iterate through the array, I would suggest to replace the lines

if fireButton = self.nodes(at: location) {
        shoot()
}

with

let nodes = self.nodes(at: location)
for node in nodes {
    if node.name == "fireButton" {
        shoot()
    }
}

And at the place where you declare fireButton assign it a name as in

fireButton.name = "fireButton" 
// just an exmaple, rather store these names as constants somewhere in your code

That's the easiest way, but you need to remember all the names you gave to your sprites. An alterantive is to create a FireButton class as a subclass of SKSpriteNode, declare fireButton as an instance of FireButton and instead of checking for names, you can do

if node is FireButton { 
    shoot()
}

Hope this helps!



来源:https://stackoverflow.com/questions/44479700/cannot-assign-value-of-type-sknode-to-type-skspritenode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!