Hi, I am new to godot and programming. After adding and deleting some code to player script I got an error in part of the code that worked fine before.
extends CharacterBody2D
var gravity = 1000
var jump_strenght = 700
var direction_x : float
var speed = 700
func get_input():
direction_x = Input.get_axis("left","right")
if Input.is_action_just_pressed("jump"):
velocity.y = -jump_strenght
func apply_gravity(delta):
velocity.y += gravity * delta
func _physics_process(delta: float) -> void:
get_input()
velocity.x = direction_x * speed
apply_gravity(delta)
move_and_slide()
After searching the solution on the internet I found information that godot hasnt loaded my variables fast enough so they have null value when my function try to use them.
So I added @onready, and it fixed the problem.
extends CharacterBody2D
@onready var gravity = 1000
@onready var jump_strenght = 700
var direction_x : float
var speed = 700
Could you help me to better understand the problem? Why do I need to use @onready and should I use in other cases? Why me changing unrelated part of the script and adding timer made the problem to show up? Or other usefull info
I think the issue may be related to when gravity is assigned. You don’t assign it in your player script, so it must be assigned a value elsewhere for the script to work. If it’s assigned in another function, and gravity is only assigned after the node is ready, then the gravity variable will not have a value when the player script tries to use it, resulting in an error?
My mistake, I accidently deleted the value assigned to gravity when copying code to paste here. Fixed already. So without @onready I get error about null value even when both variables have values assigned
I didn’t use @export but re-saving fixed the problem and now I don’t need to use @onready to run the scene. But I still dont understand why the variables had null value.
Strange, I’ve only seen that happen with previously @exported variables, using static types also prevents this from happening such as var gravity: float = 1000
Thank you, I couldn’t replicate the bug so I’am no sure what exactly caused it but when it happens next time I’ll check whether static typing solves it