☑ How to change the initialization order of scripts

Is there some way to change the order in which the initialize functions are called? I thought the “Scripts loading order” settings would do that, but seems it actually doesn’t.

Scripts are loaded in the “loading order”.

They are initialized in the order they are found in the hierarchy. Depth-first, starting at the root.

If you need to make some entities initialize before others - you could move them within hierarchy, or make an event on this.app that other script that was initialized can react and do some extra initialization, so that you have ordered stuff.

If you need to change initialize order within an entity between multiple scripts, then you can just move up/down scripts in script component.

Thanks Dave and Max.

I understand now, since I have little experience with JavaScript I didn’t remember that scripts can execute code “outside” the script functions, so it didn’t make much sense to me to have a loading order separate from initialization.

But code executed at load-time is not per instance, right? So if I wanted to initialize an entity before its parent things could get tricky, even using events if they are fired when initializing.

JavaScript by the nature is async - means the flow of execution cursor is kinda “jumping around” :slight_smile:

Perhaps parent needs something to do after child done something, right?
You could make a method on parent, and call it from child after child initialised, that would allow you to do ordered stuff the way you need to.

You can use: initialize and postInitialize methods if you have some specific ordering requirements between entities.

All initialize methods are called before any postInitialize methods.

1 Like

Ahhh, yeah, you are right, I completely forgot about the “post” methods. I’ve been learning PlayCanvas, JavaScript, HTML and CSS for a project, so I guess my brain just overflowed… :dizzy_face:

Thanks guys!