–1 vote

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?

asked Jun 27 in Engine by Huckleberry256 (21 points)

This does not belong in the "Engine" category

1 Answer

+1 vote
Best answer

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++.

answered Jun 27 by selamba (136 points)
selected Jun 30 by Huckleberry256

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.

I edited the answer.

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

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.