0 votes

Hello folks,

I am a newcomer on Godot Engine (less than a week using Godot) and
and I'm learning how to better organize the project.

My game has a common behavior among objects that is follow another object and I don't want repeat the same code for each different object. So I created a new scene with a generic Node called FollowBehavior and attached a script. The script look like this:

# FollowBehavior.gd
extends Node

var object
var target

func init(_object, _target):
    object = _object
    target = _target

func _ready():
    pass

func _process(delta):
    # MY LOGIC HERE

I added FollowBehavior as a child node in some objects and in their respective scripts I did this:

# Object with follow behavior
func _ready():
    $FollowBehavior.init(self, other_object)

Is there a better alternative for this? Is it the "best" way?

in Engine by (12 points)

I've been struggling with the exact same problem. I've done it using this node method, but also this way:

extends Node

var a_behaviour

func _init():
    a_behaviour = my_behaviour.new()
    a_behaviour.init(self)

I found that this way avoids some null object errors that can happen because of the order in which the nodes get created and the engine trying to initialize variables on objects that aren't created yet.

The downside is that you can't use the editor modify exported properties of the behaviour.

1 Answer

0 votes

you can do it like below

# FollowBehavior.gd
extends Node

var target

func _ready():
    pass

func _process(delta):
    if target == null: return
    # YOUR LOGIC HERE

and using extends

# Object with follow behavior
extends "FollowBehavior.gd"

func _ready():
    target = other_object

for more information, read this section.
http://docs.godotengine.org/en/3.0/getting_started/scripting/gdscript/gdscript_basics.html#inheritance

by (9,694 points)

But I can't have multiple extends (I got 'extends' already used for this class error).
And my objects will have multiples behaviors. Sorry for not making it clear.

in that case, probably, your way is best I think.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.