Topic was automatically imported from the old Question2Answer platform.
Asked By
Jaxp
Hello,
I’ve started to develop in Godot and I’ve finnished base tutorial.
I’m looking for something like Trait as is in PHP language. It is method of code reuse.
##Example:
I have two classes. Each of them extends different class but has exactly same function called damage(). As long as I can extend only one class, how do I re-use function damage()?
Player.gd
extends Area2D
# It has some unique code.
# ....
# And it has this function (just for example)
func damage(value):
health -= value
Mob.gd
extends RigidBody2D
# It has some unique code.
# ....
# And it has exactly same function as Player
func damage(value):
health -= value
# say_hello.gd
extends Node
# Member functions must be called on an instance after creating it using `.new()`.
func hello():
print("Hello!")
# Static functions can be called without creating an instance, but they can't reference `self` or member variables. They can also be called on instances.
static func bye():
print("Good bye!")
# user.gd
extends Node
const SayHello = preload("res://say_hello.gd")
func _ready():
# Prints "Hello!".
var say_hello = SayHello.new()
say_hello.hello()
# Prints "Good bye!". `say_hello.bye()` can do the same thing here, as static functions can also be called on instances.
SayHello.bye()