How do I initialize global variables of a scene script without using the editor?

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

How do I initialize variables of a scene script without using the editor?

I have a grid class with two members.

public int size_x and public int size_y. It uses these variables to setup an array of cells in its _Ready() function. I can change size_x from the editor but how can I change size_x via script before the _Ready function is called?

PackedScene gridscene = (PackedScene) ResourceLoader.Load("res://Grid.tscn");
//gridscene.size_x=42;
//gridscene.size_y=42*2;
this.local_grid = (Grid)gridscene.Instance();

I read the manual but did not find something about this in it.

:bust_in_silhouette: Reply From: Kurotsuki

in order to declare a variable in the script but initiallize it in the editor you use export variables, in gdscript you write “export” behind “var” which makes export var my_variableand on c# you write something like this

[Export]
public int my_variable;
[Export]

I dont use c# but after looking it up i think this is how you declare an export variable in mono

:bust_in_silhouette: Reply From: rohezal

Answer from reddit:

“Until a node is added as child to a parent, Ready will not be called at all, so set the variables before yourself”.

PackedScene gridScene = ResourceLoader.Load<PackedScene>("res://Grid.tscn");
Grid grid = (Grid)gridScene.Instance();
grid.size = new Vector2(42, 42 * 2);
AddChild(grid); // _Ready method will be called after it's added to the scene tree

https://www.reddit.com/r/godot/comments/m3qg7p/how_do_i_initialize_variables_of_a_scene_script/