Adding entities in entity constructor?


(TheHuckleberryWill) #1

For some reason, using FP.world.add(new MyEntity); in another entities constructor, seems to no longer work for me…

Actually can’t remember if it ever did work… XD

Oh, it works just fine in the update function…


(Jacob Albano) #2

I would recommend putting code like that in the Entity’s added function. At that point the entity is guaranteed to be in the world, so you can use it’s own world property.


(TheHuckleberryWill) #3

Thanks! It worked :slight_smile:


(Ultima2876) #4

As a general rule, use constructors for memory allocations (eg creating an Image object) and nothing else. Have a separate setup or init function (perhaps added would do) that resets all of the variables (and this would be where you set your graphic property to the Image you created in the constructor) and then you can take advantage of entity recycling (which is a very good idea).


(Jacob Albano) #5

To take this a step further, it’s actually a good idea to do as little work as possible in constructors, as the as3 virtual machine can’t optimize them.


(Ultima2876) #6

Huh, now that I didn’t know. That said, how much code does the AS3 VM optimize? It was my understanding that it does very little optimization at all…


(Jacob Albano) #7

That I couldn’t tell you. I think it’s a matter of whether a function is executed with the JIT compiler or just interpreted. According to the performance analyzer in FlashDevelop, constructors are interpreted.


(Zachary Lewis) #8

Also, in the case of entity recycling, there’s no way to be sure the constructor will even be called. That’s why it’s crucial to perform as much setup as possible (positioning, setting properties, et cetera) in the added() function.


Entity Recycling Help
(Ultima2876) #9

So would you say overall it’s a good idea to use the added() function instead of creating a separate setup() function? I do a lot of:

(FP.world.create(BlueMushroom) as BlueMushroom).setup(50, 50);

And I’m now wondering whether using added() would save a lot of time and make my code more readable.


(Abel Toy) #10

I also use a setup function (I actually call them reset), where I set all the properties which are different amongst the recycled stuff (for example, I only create the image on the constructor). The advantage of a custom function over the added function is I can pass it custom parameters.


(Ultima2876) #11

Yeah, I realised that shortly after in the other topic where somebody (maybe the same guy?) was asking about passing parameters to recycled entities. I think generally best practice is to go with a setup/reset function.


(TheHuckleberryWill) #12

Thanks for the help!