The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

+1 vote

I need to make the simplest class in order to store parameters of objects of the same type. I created a script like this:

class_name My_Class
var a: int
var b: string
var c: float

In another script, I declare a variable with the type of my class:

var my_var: My_Class

And when I want to assign a value to any parameter,

my_var.a = 100

It gives me an error:
Invalid set index 'a' (on base: 'Nil') with value of type 'int'.

what am I doing wrong?

Мне нужно сделать простейший класс для того, чтобы хранить параметры однотипных объектов. Я создал скрипт по типу:

class_name My_Class
var a : int
var b : string
var c : float

В другом же скрипьте я объявляю переменную с типом своего класса:

var my_var : My_Class

И когда я хочу присвоить какому-либо параметру значение,

my_var.a = 100

Мне выдаёт ошибку:
Invalid set index 'a' (on base: 'Nil') with value of type 'int'.

что я делаю не так?

Чтобы это работало, нужно объявлять переменную не так:

var my_var : My_Class

А вот так:

var my_var =
Godot version 3.2.3
in Engine by (39 points)
edited by

1 Answer

+1 vote
Best answer

You need to do something like this:

class name My_Class:
    var a: int
    var b: string
    var c: float
    func _init(a, b, c):
        self.a = a
        self.b = b
        self.c = c

And in the other script write (define a, b and c before):

var my_var =, b, c)
by (255 points)
selected by

But what if I don't need to initialize all the variables at once?

Then write, for example:

class My_Class:
     var a : int
     var b : int
     func _init(b):
         self.b = b

var x =
x.a = 5
# x.b = 8 as you initialized it

(You used class_name but I don't know how it works, I always use class)

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 Frequently asked questions and 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 [email protected] with your username.