Setting variables with an inherited script

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

Say I have a script, Entity.gd. It looks like:

extends KinematicBody2D

var speed = 0
var health = 3

Now I have another script, Enemy.gd, that looks like:

extends 'res://Entity.gd'

func _ready():
    speed = 5
    health = 5

This seems like a hacky way to set variables for children. Is there a way to set the values under the extends, using something like onready?

Why do you think this is hacky?
Theoretically, using onready just adds some syntactic sugar.

DodoIta | 2018-05-21 12:23

Well if my base class has a _ready function now I’ll have to call it in the child’s _ready, which is fine and all, but it makes children a little more involved.

To me having to set variables in the _ready function is the equivalent of having to override a function by setting it in the _ready function. I am of the opinion that, since you can override functions by just having the function exist in the child, you should be able to override variables by doing the same. Is this not possible?

GammaGames | 2018-05-22 02:54

:bust_in_silhouette: Reply From: coffeeDragon

As far as I now, you should use the _init().() function,
for inheritance like behavior.

TheEntity.gd would for exmaple look like this:

extends KinematicBody2D

var speed = 0
var health = 3    

func _init(_speed = 0, _health = 3).():
speed =_speed
health = _health

TheEnemy.gd like:

extends 'res://Entity.gd'
func _init().(5, 5):
   pass

That definitely seems more proper, thank you!

GammaGames | 2018-05-23 13:39