Putting stuff in update vs added


(Lozza JP) #1

Hi I was wondering of the deal with putting things in the update vs added methods.

I was placing a world.getInstance(“player”) line so I can reference the player in other classes, I found putting in the constructor method causes a null pointer crash. But it works in update, but I thought putting it in update would mean calling it 60 times a second or the fps rate.

I just found it works in added, is it best to place it in added?


(Martí Angelats i Ribera) #2

Yes. Added is only called once (right after adding the Entity to a World). Using it in update() only makes you do the same multiple times (once per frame) and it’s not used.


(Jacob Albano) #3

This is a fiddly question because it’s possible that it won’t always work in added() either. First, though, let me address the matter of the crash when you put that line in the constructor.

When an entity is in a world, meaning it’s being updated and rendered, the world variable is guaranteed to not be null; it points to the world that contains the entity. If the entity hasn’t been added yet, the world variable will always be null. Even if you create an entity and immediately add it to the world, accessing the world property in your constructor will always cause a null reference error.

The first time that world will reference a valid object is when used in the added() function. This is theoretically when you can check the world for other entities; in your case world.getInstance("player"). The potential problem is that if the two entities are added out of order (if “player” is added after the one that searches for its instance) you’ll still get a null reference back from that function – though it’ll be the entity you searched for in this case, not the world.

What I usually do in this case is the following. It’s a bit of as3 short-circuiting magic.

override public function update():void
{
    this.player = player || world.getInstance("player") as Player;
    if (player != null) // do stuff with player
}

The way this works is by assigning the player variable to the first “truthy” value. Since null converts to false, the second statement will only run if player is null, after which point it will be a valid value and stop the getInstance() call from running.

It’s the best of both worlds; you don’t have to worry about the order in which each entity is added, and it avoids the relatively expensive instance lookup if it isn’t required any longer. Plus, that one-liner is just so good lookin’.


(Lozza JP) #4

wow that is great, never would have thought to use a logical or during assignments!!

Thanks jacob!