Astrum
Astrum

Reputation: 375

instance frame type when not in a function error

I am making a game in which objects spawn on the map in a certain location and I have multiple functions for different objects and needed a reference so I put my code outside of the function to widen its scope but now I get an error that says

Instance type 'frame' cannot be used on type 'Levelunit'

If i put it back into the function it is completely fine but it seems to have a problem when I put it outside the function. Here is my code:

let yAxisSpawnLocations: [CGFloat] = [0]
let xAxisSpawnLocations: [CGFloat] = {

    var spawnLocations:[CGFloat] = []   //Create 5 possible spawn locations
    let numberOfNodes = 5

    for i in 0...numberOfNodes - 1 {

        var xPosition = (frame.maxX) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

        xPosition += thePlayer.size.width/2

        xPosition -= frame.maxX/1.6
        spawnLocations.append( xPosition )

    }

    return spawnLocations

}()

I looked it up and didn't quite understand the answer given. Could someone tell me what i'm doing wrong please.

BTW, LevelUnit is the name of my class.

Upvotes: 1

Views: 39

Answers (1)

Whirlwind
Whirlwind

Reputation: 13675

You are trying to use self before Levelunit has be fully initialized. For example, this is one place where you use self implicitly:

var xPosition = (frame.maxX) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

it is the same as:

var xPosition = (self.frame.maxX) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

So, what you can do is to initialize this property at Levelunit initializer (which I would skip if you don't want to have a dance with automatic initializer inheritance rules), or to initialize it in didMoveToView, which will work fine. If I am not wrong, Levelunit is probably subclass of a SKScene, right? If so, just do this:

//Define a property of Levelunit like this

 var xAxisSpawnLocations:[CGFloat] = []

Then just initialize it inside of didMoveToView:

let numberOfNodes = 5

for i in 0...numberOfNodes - 1 {

    var xPosition = (self.frame.maxX) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

    xPosition += thePlayer.size.width/2
    xPosition -= frame.maxX/1.6
    xAxisSpawnLocations.append( xPosition )

}

Upvotes: 1

Related Questions