【问题标题】:Call a function from a different swift file从不同的 swift 文件调用函数
【发布时间】:2021-04-05 21:26:57
【问题描述】:

XCode 版本 12.4 (12D4e)

Functions.swift 中的第一个 SKScene 类包含我想在不同的 SKScene 类中调用的 buildBackground 函数。

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()”行得到“Cannot find 'Functions' in scope”。运行构建后,我收到消息“背景已加载”,所以我猜该函数被调用,但是,我的壁纸 SKSpriteNode 没有出现在我的场景中。在我尝试在 Room.swift 类中移动 buildBackground 方法后,一切正常,但我的项目中有很多不同的场景(Room1、Room2 等),所以我不想在每个文件中复制粘贴这个方法.

【问题讨论】:

  • 创建一个基本的 SKScene 文件。并在您需要 SKScene 并使用构建后台功能时继承它。

标签: swift skscene


【解决方案1】:

由于您要覆盖公共函数,您可能需要使用self

self.functions.buildBackground(...)

【讨论】:

  • 我试过但得到了相同的结果。调用了 buildBackground 函数,但 SKnode 没有出现在场景中。
猜你喜欢
  • 1970-01-01
  • 2023-01-23
  • 2021-10-05
  • 2021-07-27
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
相关资源
最近更新 更多