Can scripts or GameObjects inherit from each other?

I was wondering if there is the possibility of inheritance in Defold. So I took a look at the Side Scroller Tutorial, cause I remembered that there is a normal star and a bonus star. Both stars have their own script, but 95% of their code is exactly the same. I personally don’t like repetitive code, so inheritance would be really nice in this case.

My question is now: Can scripts or GameObjects inherit from each other?

No, what you need to do is divide it into behaviours, where different scripts are responsible for different things. In that particular case though - if I remember the purpose of bonus stars correctly - you could have one script but with speed and points as properties that you set from the editor.

1 Like

Thanks a lot for answering :slight_smile:

For my case, I should probably use the division into behaviours. I’m trying to understand how that works. But it’s not 100% clear to me

So you mean for example:

I have two scripts:

  • move_left.script <-- which lets the star move to the left, each update cycle
  • reward_points_on_collection.script <-- which rewards points, when the spaceship collects the star

I would add both scripts then to star.go and bonus_star.go and set the parameters in the factory.

Is that right?

Or is there an example on the web? I was trying to search for something on google, but wasn’t sure what to search for.

Yes, that is exactly what I mean!
You could even call the first script something like “can_move.script”, have the speed as a property and share that code between stars and the space ship. The only difference would be the spaceship would have it’s speed set from another script that takes keyboard input and the stars would have the speed set at creation time.

2 Likes

You can either compose behavior with separate scripts components and prime them with data through script properties (see http://www.defold.com/ref/go#go.property) or you can compose several interacting game objects in collections.

1 Like