Best way to declare instance variables?

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

Hi, I started out with godot recently, coming from a python background. I like to think of godot scripts as the classes in my project, I’m not even using inner classes. A lot of my classes require instance variables, which in python I would just declare using “self” in the constructor. This is pretty much what I’m doing in godot at the moment, however I have to declare them before I can assign them with _init.

Here’s what I mean:

extends Node2D

var attach_point: Vector2
var start_vec: Vector2
var end_vec: Vector2
var strength: float

func _init(attach_point, start_vec, end_vec, strength):
	self.attach_point = attach_point 
	self.start_vec = start_vec
	self.end_vec = end_vec
	self.strength = strength

Is there a way to do this in one line? I am aware that I can just assign them after instancing the script, however I prefer to use, param2 …)

Note 1: if you attach a script to a node, I’m not sure _init is allowed, because in those cases the scene loader needs to call a parameterless constructor (so at best your constructor won’t be called actually, unless you instance that script by code).

Note 2: you don’t have to extend nodes each time, you can also not extend anything (which defaults to extending Reference). It’s important to know this because there is a difference between Object (which nodes derive from) and Reference (which resources derive from). The first is explicitely freed unless inside the tree, the second is reference-counted.

Note 3: using self to assign variables in Godot is very different from Python. In Godot, self.x means setting a variable from outside the class. When using it inside properties with getters and setters, this can cause an infinite call to such setter.

Zylann | 2019-12-21 10:37

:bust_in_silhouette: Reply From: Zylann

You have to declare them outside functions, there is no way to do otherwise. You can initialize them to default values though.

Alright, that clears it up, thank you. the variables remain inside the function scope, even if it’s an _init() function. I guess I’ll just continue doing it this way, since the values change with every instance.

redsharktooth22 | 2019-12-21 11:47