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’.