问题描述
XCode 版本 12.4 (12D4e)
Functions.swift 中的第一个 SKScene 类包含了 buildBackground 函数,我想在不同的 SKScene 类中调用它。
class Functions: SKScene {
func buildBackground(backgroundPath: String){
let texture = SKTexture(imageNamed: backgroundPath)
let background = SKSpriteNode(texture: texture)
background.size = CGSize(width: 512,height: 512)
background.position = CGPoint(x: 0,y: 0)
background.name = "BACKGROUND"
addChild(background)
print("Background loaded")
}
}
我正在尝试在 Room.swift 文件的第二个 SKScene 类中调用此函数
我在 Room 中创建了一个 Functions 实例,并像这样调用了我的函数:
public class Room: SKScene {
let functions = Functions()
override public func didMove(to view: SKView) {
functions.buildBackground(backgroundPath: "roomBackground")
}
}
我在“let functions = Functions()”行上看到“在范围内找不到‘函数’”。运行构建后,我收到消息“背景已加载”,所以我猜是调用了该函数,但是,我的壁纸 SKSpriteNode 没有出现在我的场景中。在我尝试在 Room.swift 类中移动 buildBackground 方法后,一切正常,但是我的项目中有很多不同的场景(Room1、Room2 等)所以我不想在每个文件中复制粘贴这个方法.
解决方法
由于您要覆盖公共函数,因此您可能需要使用 self
:
self.functions.buildBackground(...)