ios - 从子 SKSpriteNode 读取值

标签 ios swift skspritenode sknode

基本卡片对象:

import Foundation
import SpriteKit

class Card: SKSpriteNode {
    var cardValue:Int = 0

    init() {
        cardValue = 10
    }
    ...
}

当它是 SKNode 的子节点时,为什么我无法读取它?使用 lldb 调试时,它向我显示了整个对象中的值,但我无法访问它:

(lldb) p handsOnScreen.children[0]
(BlackJack.Card) $R0 = 0x00007f84937a21a0 {
  SpriteKit.SKSpriteNode = {
    SKNode = {
      UIResponder = {
        NSObject = {
          isa = Blackjack.Card
        }
        _hasAlternateNextResponder = false
        _hasInputAssistantItem = false
      }
      _parent = 0x00007f8493708b60
      _children = nil
      _actions = nil
      _keyedActions = nil
      _keyedSubSprites = nil
      _info = nil
      _attributeValues = nil
      _name = nil
      _userData = nil
      _constraints = nil
      _version = 17096000
      _userInteractionEnabled = false
      _reachConstraints = nil
    }
    _light = nil
    _shouldRepeatTexture = false
  }
  cardValue = 10
  ...

看到输出后,我想我可以试试这个:

(lldb) p handsOnScreen.children[0].cardValue
error: <EXPR>:1:35: error: value of type 'SKNode' has no member 'cardValue'

我做错了什么?

最佳答案

您必须将 SKNode 转换为 Card 才能访问其属性。

if let card = handsOnScreen.children[0] as? Card {
  print(card.cardValue)
}

我使用 if let 语句而不是强制解包 (as!) 以确保对象位于 children[0] 时的安全碰巧不是 Card

关于ios - 从子 SKSpriteNode 读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979538/

相关文章:

ios - 快速更新 Realm 主键值

ios - SKView CALayer 上方的 SpriteKitNode

ios - 为 SKLabelNode 设置背景颜色?

swift - 如何从内存中清除 SKSpriteNode?

ios - 我的应用程序中需要核心数据吗?

iphone ios xcode 4.2 - EXC_BAD_ACCESS 信号

ios - 如何为需要下拉到向上的 UIview 创建动画?

ios - 为不同设备获取相同的 uibutton 中心值

iphone - 推沃什 : Swift Code

ios - 如何在tableview Cell中设置tableView的自动高度?