Search code examples
swiftsprite-kitsklabelnode

How to cache or preload SKLabelNode font in spritekit


I want to load the font once and use it for the other sklabel nodes

let originalLabel: SKLabelNode = SKLabelNode(fontNamed: "fontName");

and later

var labelNode = originalLabel;
var labelNodeSecond = originalLabel;

but that gives the following error

Attemped to add a SKNode which already has a parent: SKLabelNode


Solution

  • You can set the font once by initializing an UIFont:

    let yourFont = UIFont(name: "yourfontName", size: 17)
    
    var firstLabel = SKLabelNode(fontNamed: yourFont?.fontName) 
    var secondLabel = SKLabelNode(fontNamed: yourFont?.fontName)
    

    That way, you only set the font once and the SKLabelNodes don't have to load it by themself.