0

I am currently working on a game menu with 3 options: New game, Load Game, and Options. I have also attached a piece of code to New Game to make it print something for now. I have also added a custom font, and I made some code which is supposed to change the default font to the font I loaded into my res:// folder. Here is the code:

    extends Button


# Declare member variables here. Examples:
# var a = 2
# var b = "text"

#-----Font section------#
func _fonts():
    var font = DynamicFont.new()
    font.font_data = load("res://Mandala Vintage.ttf")
    $Button.set("custom_fonts/font", font)

#------Font section over-----#
# Bind "New game" to key press: enter
var current_font = null
var unused_font = load("res://Mandala Vintage.ttf")

func _process(_delta):
    if Input.is_action_pressed("ui_accept"):
        var dynamicFont = get("custom_fonts/font")
        current_font = dynamicFont.font_data
        dynamicFont.font_data = unused_font
        unused_font = current_font
# Done

# Called when the node enters the scene tree for the first time.
# Create a new button
func _ready():
    var button = Button.new()
    button.text = "New Game"
    button.connect("pressed", self, "_button_pressed")
    add_child(button)
    
 # Add a function to the button
func _button_pressed():
    print("Create a new window here")

The font part isn't working. Here is my output: Output

RockZombie
  • 101
  • 1
  • 9

1 Answers1

0

You say:

(the) code (…) is supposed to change the default font to the font I loaded

The font of what node?

  • The one where the code is running?

    • Did you forget to trigger "ui_action"? If you did, that explains that nothing happened. Trigger "ui_action".
    • You did trigger "ui_action" and got errors? Probably you didn't set a font to the node to begin with, so you got a null reference here var dynamicFont = get("custom_fonts/font") and thus current_font = dynamicFont.font_data fails. You need to handle the case where get("custom_fonts/font") is null.
    • You did trigger and nothing happened? The font you set to the node to begin with is exactly the same you swapping it with. So you see no change. Try setting a different font.
  • The one you created?

    You created that button and forgot about it.

    Would _font (if it did run, notice that nothing in the code calls it) change the font of the button you added? Turns out no. You didn't provide a name for the button you added. And $Button in _fonts would try to get it by name ($Button is equivalent to get_node("Button")). Since there is no such child node called "Button", that fails.

    So, either give a name to the button, or keep a reference to it in a variable you can access from _font or wherever you need it. And if you want _font to run, when? Call it (Edit: or connect a signal to it).

Theraot
  • 31,890
  • 5
  • 57
  • 86