Why is this variable null?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Derik Hammer

When I run my game, the “loadOut” variable is NULL, in the _load_stats func, when it is instantiated. My understanding is that my getter should prevent any such NULL value. Can anyone please help me understand this behavior?

Godot Engine v3.2.1.stable.official

extends Node2D

var loadOut setget , _get_load_out
var _default_load_out = preload("res://equipment/load-outs/player-load-out.gd").new()

func _ready():
	pass

func _init():
	_load_stats()
    
func _get_load_out():
	return loadOut if loadOut != null else _default_load_out

func _load_stats():
	for i in loadOut.stats:
		self.set(i, loadOut.stats[i])
:bust_in_silhouette: Reply From: Becbunzen

You do not have a setter? Try this:

var loadOut setget _set_load_out, _get_load_out

plus define the setter. Also might help to set it to an initial value.

Edit: If you only want a getter, you have a space too much, should be

var loadOut setget ,_get_load_out

Unfortunately, I receive the same behavior with the setter and the space removed.

Added code:

var loadOut setget set_load_out,_get_load_out

func set_load_out(value):
	loadOut = value

Derik Hammer | 2020-06-03 17:49

Try setting a default value already in the declaration, and check if it is ever changed.

Becbunzen | 2020-06-03 19:18

Is there a way to set a default value in-line with a setget?

Image of the default value having a value. Also, break point confirms entry into the getter.

Derik Hammer | 2020-06-03 20:39

Yes, you can set default. Like this:

var loadOut = 0 setget set_load_out,_get_load_out

Becbunzen | 2020-06-03 21:52

:bust_in_silhouette: Reply From: Derik Hammer

I solve the problem. Thank you to Becbunzen for helping out.

I revised my code to this:

func _ready():
	_load_stats()

func _init():
	pass

Because load stats, in the init, was loading prior to default load out being ready. I noticed that, if I continued the program through a bunch of the iterations in load stats, then loadOut would be returning correctly.

By loading the stats on ready instead, I am effectively delaying the call and letting the default load out populate.

Great that you found a solution! See my comment on the other thread about default value as well, if needed.

Becbunzen | 2020-06-03 21:52