Why Can't I Access Properties on my custom class?

Godot Version

4.3

Question

I am making a tile-based game (well let’s call it a prototype) and so I have a big array of tiles. I made a Tile class here that should work:

class_name Tile extends Object

var id: int
var pos: Vector2i
var owner: int = 0
var building_id: String # Probably not gonna be a string!
var elevation: int = 0

func _init(_id: int, map_size: Vector2i, _owner: int = 0, _elevation: int = 0,
		_building_id: String = "empty") -> void:
	id = _id
	pos = Vector2i(_id % map_size.x, floor(_id / map_size.y)) #malo by fungovat
	owner = _owner
	elevation = _elevation
	building_id = _building_id
	print("Tile created: id=", id, " pos=", pos, " owner=", owner, " elevation=", elevation)

I then create a bunch of tiles here:

extends Node

var master_board: Array = [Tile] # Vsetky tiley, bud proste dlhy array alebo arraye (riadky) tileov
const MAP_SIZE = Vector2i(10,10)

func _ready() -> void:
	for i in range(0, MAP_SIZE.x*MAP_SIZE.y):
		var tile = Tile.new(i, MAP_SIZE)
		master_board.append(tile)

Now I hope I’m not completely misunderstanding the topic, but there’s no reason why something like this shouldn’t work.

extends TileMapLayer


# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	for i in range(Board.master_board.size()):
		var t = Board.master_board[i]
		set_cell(t.pos, 0, Vector2i(0,0))

However when I try to access any of the properties, it throws this error:

Invalid access to property or key 'pos' on a base object of type 'GDScript'.

Again, I hope I’m not misunderstanding the topic but WHY? How else am I supposed to do things? Thanks for any help!

Try modifying this line:

var t = Board.master_board[i]
var t = Board.master_board[i] as Tile

as is effectively a safe way of casting. If the variable can be cast to the specified type, then great, otherwise the assignment is null.

You are inserting the Type itself Tile as the first element of the array. If you want a typed array you can specify it within the type declaration

 var master_board: Array[Tile] = [] # No elements
1 Like