When I inherit a script, how do I override the variables in the base script?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Gensoukyou1337

Let’s say I have a base GDScript I want to inherit from:

base.gd

extends KinematicBody2D

var WALK_MAX_SPEED = 120

func _ready():
	pass

func _physics_process(delta):
	pass

func _input(event):
	pass

func get_horizontal_movement():
	var x_dir = 0
	if Input.is_action_pressed("move_right"):
		x_dir = 1
	elif Input.is_action_pressed("move_left"):
		x_dir = -1
	return x_dir * WALK_MAX_SPEED

Can I modify the WALK_MAX_SPEED variable directly from the inheriting script, or do I set it in _ready()? As in:

extending.gd

extends "res://base.gd"

func _ready():
    WALK_MAX_SPEED = 200

"""Rest of the script"""
:bust_in_silhouette: Reply From: Xrayez

Can I modify the WALK_MAX_SPEED variable directly from the inheriting script

Yeah, you can do whatever you want with this variable in extending scripts, including what you’ve done in _ready() callback. But you can’t re-declare the same variable inside extended script though.

You might want to look at overriding _init() method to reinitialize the variable on creation:

func _init(max_speed):
    WALK_MAX_SPEED = max_speed

var character = Character.new(200)

If for some reason you want to restrict the access to the variable from outside the script, you declare your variable as:

var WALK_MAX_SPEED = 120 setget set_max_walk_speed, get_max_walk_speed

func set_max_walk_speed(p_speed):
    # You can encapsulate how you would want to set maximum speed internally
    WALK_MAX_SPEED = max(0, p_speed) 
    
 func get_max_walk_speed():
    return WALK_MAX_SPEED

So when you access WALK_MAX_SPEED from outside the script like:

character.WALK_MAX_SPEED = 200

What it will do is actually call set_max_walk_speed() method to set speed. Take in mind that these set/get will only get triggered from outside the script, you’ll need to use actual methods inside the script then.