Error drawing lines on grid - tetris recreation

Godot Version

4.6

Question

I am following a tutorial on how to recreate Tetris.

I am on the part of the tutorial where they are drawing the grid. However, my code keeps coming up with an error on “grid_lines.add_child(line)”

Note: The tutorial is using 4.3

extends Control

const GRID_WIDTH: int = 10
const GRID_HEIGHT: int = 20
const BLOCK_SIZE: int = 30

var grid: Array\[Array\] = [ ]

@onready var game_area: ColorRect = $GameArea
@onready var grid_lines = $GameArea/GridLines

func \_ready() → void:
initialize_grid()
draw_grid_lines()

func initialize_grid() → void:
   for x in range(GRID_WIDTH):
       var column: Array\[Variant\] = [ ]
       for y in range(GRID_HEIGHT):
       column.append(null)
       grid.append(column)

func draw_grid_lines() → void:
     for x in range(GRID_WIDTH + 1):
        var line: Line2D = Line2D.new()
        line.add_point(Vector2(x \* BLOCK_SIZE, 0))
        line.add_point(Vector2(x \* BLOCK_SIZE, GRID_HEIGHT \* BLOCK_SIZE))
        line.width = 1
        line.default_color = Color.WHITE
        grid_lines.add_child(line)

     for y in range(GRID_HEIGHT + 1):
	   var line:Line2D = Line2D.new()
	   line.add_point(Vector2(0, y * BLOCK_SIZE))
	   line.add_point(Vector2(GRID_WIDTH * BLOCK_SIZE, y * BLOCK_SIZE))
	   line.width = 1
	   line.default_color = Color.WHITE
	   grid_lines.add_child(line)

What does the error say exactly?

Attempt to call function ‘add_child’ in base ‘null instance’ on a null instance.

That means your grid_lines variable is null at runtime. You assign the variable in this line:

@onready var grid_lines = $GameArea/GridLines

So check if the node exists in this relative position in the tree: $GameArea/GridLines. Most likely not, due to either changing the name of the nodes, or the tree structure.
You can access the nodes as unique names to avoid that, have a read here:

Or I’d recommend to use @export var instead of @onready var:

1 Like

It worked :man_facepalming:

1 Like