daniel
daniel

Reputation: 966

Why is SKSpriteNode(fileNamed:) generating nil in iOS using Swift?

Why is init(fileNamed:) of SKSpriteNode generating a nil?

I've tried the following code. I show only the code that is related to the problem:

let road = SKSpriteNode(fileNamed: "road.png")

override func didMove(to view: SKView) {

    print("road", road as Any) // road nil
    if let road = self.road {
        road.position = view.center
        road.physicsBody = SKPhysicsBody(rectangleOf: road.size)
        print(road.physicsBody?.isDynamic as Any, "!")
        road.physicsBody?.pinned = true
        addChild(road)
    }

}

I get a nil regardless of whether the image file is a regular png or an animated png file.

Upvotes: 2

Views: 276

Answers (1)

yrk
yrk

Reputation: 410

You should use SKSpriteNode(imageNamed:) instead of SKSpriteNode(fileNamed:).

SKSpriteNode(imageNamed:) - loads image as texture for you and creates a node.

SKSpriteNode(fileNamed:) is actually init method from SKNode, as it says in official doc:

init?(fileNamed: String) Creates a new node by loading an archive file from the game’s main bundle.

So there are two different methods (constructors), from two different classes, and even though one inherit from another they should not be confused.

Upvotes: 1

Related Questions