0 votes

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 my_class.new(param1, param2 ...)

in Engine by (14 points)

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.

1 Answer

+1 vote

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

by (27,896 points)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.