A query to store variable

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

Hi everyone!
I have around 30 kinds of enemy’s and each with approx. 10 levels. And each of the level has some variables like:

damage = [1,2,3,4]
attack_names = ["atk1', "atk2", "atk3'. "atk4"]

earlier I had decided to make a dictionary for each level’s variables.
And now I think making a class for enemy and an object for each level would be better. But I don’t know how to create a class how to make an object out of the class. Please tell me about it

:bust_in_silhouette: Reply From: TimiT

Hello. You can find it here

All GDScript files are classes. You can create “enemy.gd” file and here use


func _init():

Variables and Methods

var health = 100

func attack(foo):

And create object using this

const Enemy = preload("enemy.gd")

func _ready():
    var enemy = Enemy.new()

More info about classes (and inner classes) you can read in documentation (link above)
Hope it helps

:bust_in_silhouette: Reply From: Wakatta

The benefit of classes are inheritance, function calls, etc. And you may not know this but you’re already familiar with classes if you used GDscript with nodes as they function more or less the same way

Try to avoid using classes if your intention is to store data as even though the difference is micro classes take longer to construct.

To create a class

class EnemyClass:
    enum ATTACKS {atk1, atk2, atk3, atk4}
    var hp = {"max":10, "amt":10}
    var damage = [1,2,3,4]

    # what todo on enemy created
    func _init():

    func heal(amt):
        hp.amt += amt
        if hp.amt >= hp.max:
            how.amt = hp.max

    func receive_damage(dmg):
        hp.amt -= dmg
        if hp.amt <= 0:

To use a class by creating an object

func ready():
    var enemy1 = EnemyClass.new()

    #Class aren't much different from Dictionaries when manipulating values.

Further information

Means having 300 dictionaries is better than having one enemy class and having 300 enemy objects out of it. I am not interested to save enemy’s stats.

Help me please | 2021-06-20 03:06

I don’t believe that class can be accessed without loading the class file with load(), or adding a class_name definition at the top of the class file. class is used for nesting one class inside another. Load the class file using onready var class_file=load("res://gdrespath") and then use class_file.EnemyClass.new() to instantiate.

Or fix the class file as below to access the class globally :


class_name EnemyClass

enum ATTACKS {atk1, atk2, atk3, atk4}
var hp = {"max":10, "amt":10}
var damage = [1,2,3,4]

# what todo on enemy created
func _init():

wyattb | 2021-06-20 04:36