How do you call class methods from an external GDScript file?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By t_monkeyman
:warning: Old Version Published before Godot 3 was released.

Quick question from a Godot newbie. I’m having trouble calling a method from a GDscript custom class.

Tile.gd is a simple class I made with just a few getter methods, which is loaded by gameboard.gd.

However, I’ve been trying to access any of the class properties in a new Tile object, but I keep receiving a Nonexistent function error from the debugger.

Please take a look at my script files:

Tile.gd

const TileScene = preload("res://scenes/entities/Tile.tscn")

enum TYPES {NULL, GRASS, WATER}

class Tile:
    var type
    var isWall
    var sceneInstance

    func _init(type = TYPES.NULL, isWall = false):
        self.type = type
        self.isWall = isWall
        self.sceneInstance = TileScene.instance()
        self.sceneInstance.get_node("TileSet").set_frame(self.type)

    func get_type():
        return self.type

    func isWall():
        return self.isWall

    func get_scene():
        return self.sceneInstance

gameboard.gd

extends TileMap

var board = null
onready var Tile = preload("res://src/Tile.gd")

func _ready():
    var a = Tile.new()
    print(a.isWall())       # <<< "Nonexistent function" error
    print(a.get_scene())    # <<< Also a "Nonexistent function" error
    print("ready!")

After running the project, the debugger displays: Invalid call. Nonexistent function 'get_scene' in base 'Reference (Tile.gd)'.

I’ve been scratching my head for a while trying to figure out why I’m unable to call any of the class methods.

If anyone could help guide me in the right direction, I’d really appreciate it.

:bust_in_silhouette: Reply From: mollusca

You’re creating an instance of the script, not the class Tile. Try replacing

var a = Tile.new()

with:

var a = Tile.Tile.new()

Ah, you are absolutely correct. That was kind of a “duh” moment on my part. I didn’t realize I was creating a new script instance. That makes a lot of sense, otherwise, how else would I call my enum than “Tile.TYPES”. Thanks for the help!

Corrected code:

gameboard.gd

extends TileMap

var board = null
onready var Tile = preload("res://src/Tile.gd")

func _ready():
    var tile = Tile.Tile.new()
    print(tile.get_scene())    # Output: [Node2D:570]
    print("ready!")

t_monkeyman | 2017-07-01 14:36