0 votes

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()
Godot version 3.2.3
in Engine by (41 points)
edited by

1 Answer

0 votes
Best answer

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)
by (217 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 = 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)

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.