OOP in GDScript

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

I’m creating a script that stores stats for different playable characters in my game. Each playable character has the same structure (name, speed, weapon(s), abilities, etc.). I wondering, how do you use object-oriented programming (OOP) in GDScript?
If this was JavaScript, it would look something like:

var constructor = function(param1,param2) {
this.param1 = param1,
this.param2 = param2,
var instance = constructor('value', 'value');

How can this be recreated in GDScript so it has the same functionality?

This does not belong in the “Engine” category

selamba | 2020-06-27 15:51

:bust_in_silhouette: Reply From: selamba

Completely rewriting the answer since the question wasn’t clear.


class_name CharacterStats

var name: String = "N/A"
var health: int = -1
var mana: int = -1

func _init(name: String, health: int, mana: int):
    self.name = name
    self.health = health
    self.mana = mana

func get_stats() -> String:
    return name + " has " + str(health) + " health and " + str(mana) + " mana."

func print_stats() -> void:


extends Node

var characters_data: Dictionary = {
    "Cole": CharacterStats.new("Cole", 100, 30)

func _ready():
    characters_data["Kaya"] = CharacterStats.new("Kaya", 40, 150)
    if characters_data["Kaya"].has_method("print_stats"):

CharacterStats.gd is not attached to any node (it also doesn’t extend anything), but Node.gd is attached to a Node. In this design CharacterStats.gd is sort of a header-file, like in c++.

Thanks for answering, but this wasn’t exactly what I was going for. Sorry if I wasn’t very clear.

I want to create a dictionary that stores all of the character stats. I could do something like this:

var character_data = {

But that would be repetitive and take a very long time. I want to make a function that takes in the separate stats as parameters, compile them into a dictionary, and then return the dictionary, so its entries can be accessed. I originally tried this:

func character_new(name:String,speed:int,...)
   var character_data = {
   return character_data
var character1 = character_new('Name',400...)

But it didn’t work. How can I make something like this that works? Thanks, once again.

Huckleberry256 | 2020-06-28 16:15

I edited the answer.

selamba | 2020-06-28 18:19

That makes a lot of sense! Thanks so much!!!

Huckleberry256 | 2020-06-30 16:21