custom classes

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

I need to make the simplest class in order to store parameters of objects of the same type. I created a script my_class.gd 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?


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

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 = My_Class.new()
:bust_in_silhouette: Reply From: abelgutierrez99

Hello,
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 = My_Class.new(a, b, c)

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

ateff | 2020-12-22 06:24

Then write, for example:

class My_Class:
     var a : int
     var b : int
     func _init(b):
         self.b = b
     
var x = My_Class.new(8)
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)

abelgutierrez99 | 2020-12-22 09:03