0

How does one override a function that was defined in a parent script?

Here's my parent script:

# Object.gd

extends Area2D

var id = 0
var coords

func _ready():
    assign_values()

func assign_values():
    var a = global_position.x
    var b = global_position.y
    #cantor pairing function
    id = (a + b) * ( a + b + 1) / 2 + b
    coords = global_position

Here's the script that extends the parent script. I am trying to overwrite the assign_values() function in the new script to calculate the id differently. When I call assign_values in the extended script the weirdest thing happens. I can't print the individual components of the coords vector anymore, even though the type checks out and printing the vector works fine, too.

# Road.gd

extends "res://Object.gd"


func assign_values():
    coords = Vector2(128, 96)
    var a = coords.x # <- Here be Dragons
    var b = coords.y
    #cantor pairing function
    id = (a + b) * ( a + b + 1) / 2 + b
   
    print(typeof(coords)) # prints 5 -> Vector2 type
    print(coords) # prints (128, 96), looks alright
    print(coords.x) # Boom! crashes with error Invalid get index 'x' (on base: 'Nil').




I'm at a loss why I get this weird vector error. Notably, the whole thing works if I just write a new function in the extended script, func assign_new_values(), but I am not sure this is the right way to do this. I expected Godot to override functions from parent scripts if they are just declared again, but that does not seem to work. What is the proper way to do this? Could not find anything in the documentation..

mandmeier
  • 355
  • 5
  • 16
  • 2
    Hi, I am (fortunately) unable to reproduce this issue. I created a new project and copy and pasted the scripts you have posted above. It worked as expected and printed the values: `5`, `(128, 96)`, and `128`. – hola Dec 10 '21 at 08:21
  • Thanks for trying! In that case it might be my settings or god knows what. Not looking forward to troubleshooting this... – mandmeier Dec 10 '21 at 18:37

0 Answers0