【发布时间】:2016-05-10 03:08:05
【问题描述】:
我正在使用 GameplayKit 和 SpriteKit 框架编写游戏。在 Apple 关于 GameplayKit 的示例中,您经常会看到以下内容:
class PlayerEntity: GKEntity {
// MARK: Components
var renderComponent: RPRenderComponent {
guard let renderComponent = componentForClass(RPRenderComponent.self) else {
fatalError()
}
return renderComponent
}
var stateMachineComponent: RPStateMachineComponent {
guard let stateMachineComponent = componentForClass(RPStateMachineComponent.self) else {
fatalError()
}
return stateMachineComponent
}
// MARK: Initialisation
override init() {
super.init()
let renderComponent = RPRenderComponent()
renderComponent.node.entity = self;
let stateMachineComponent = RPStateMachineComponent(states: [
RPPlayerStandingState(entity: self),
RPPlayerFallingState(entity: self),
RPPlayerBouncingDownState(entity: self),
RPPlayerBouncingUpState(entity: self),
RPPlayerJumpingState(entity: self),
RPPlayerBoostState(entity: self)
])
addComponent(renderComponent)
addComponent(stateMachineComponent)
}
}
组件在它们所属的类的初始化过程中被创建和初始化,并通过addComponent(component: GKComponent)添加到组件数组中。
为了使这些组件可以从类外部访问,Apple 示例始终使用调用 componentForClass() 的计算属性来返回相应的组件实例。
然而,渲染组件是“每帧”访问的,这意味着在每个更新周期中我都需要调用渲染组件,这将导致调用计算属性,这在我看来会导致额外且可避免的处理负载。
调用看起来像:
func update(withDeltaTime time: NSTimeInterval) {
playerEntity.renderNode.DoSomethingPerFrame()
}
而不是这个,我这样做如下:
class PlayerEntity: GKEntity {
// MARK: Components
let renderComponent: RPRenderComponent
var stateMachineComponent: RPStateMachineComponent!
// MARK: Initialisation
override init() {
renderComponent = RPRenderComponent()
super.init()
renderComponent.node.entity = self
stateMachineComponent = RPStateMachineComponent(states: [
RPPlayerStandingState(entity: self),
RPPlayerFallingState(entity: self),
RPPlayerBouncingDownState(entity: self),
RPPlayerBouncingUpState(entity: self),
RPPlayerJumpingState(entity: self),
RPPlayerBoostState(entity: self)
])
addComponent(renderComponent)
addComponent(stateMachineComponent)
}
}
我没有使用计算属性访问组件,而是在我的类中持有对它的强引用。在我看来,我在调用计算属性时避免了额外的开销,因为我避免了“计算”。
但我不太清楚为什么 Apple 使用计算属性来做到这一点。也许我对计算属性完全错误,或者只是因为这是编写该示例的人的编码风格!?
计算属性会影响性能吗?它们是否自动意味着更多的开销?
或者:
使用这样的计算属性是否可以且“安全”(就资源而言)? (在我看来,计算属性尽管害怕一个相当优雅的解决方案,顺便说一句。)
【问题讨论】:
标签: ios swift properties