I’m not even sure if this is the “correct” way of doing it but I have an array in the World that I want to be updated by functions of Entities spawned in that World.
How do you go about doing this?
I’m not even sure if this is the “correct” way of doing it but I have an array in the World that I want to be updated by functions of Entities spawned in that World.
How do you go about doing this?
Make the array public, then from within the entity’s code cast the world
property to the correct world class, and access the property:
public class MyWorld extends World {
public var thingamajigs:Vector.<Whatchamacallit>;
}
public class MyEntity extends Entity {
override public function update():void {
if (condition_is_met) {
(world as MyWorld).thingamajigs[0].pericombobulate();
}
}
}
Two things though: firstly, it’s generally better not to access properties themselves, but rather delegate to functions. This means that the logic inside the external class (here: entity) is simpler, and you can handle parameter validation and checking inside the function rather than in the calling code. Simple example:
public class MyWorld extends World {
private var thingamajigs:Vector.<Whatchamacallit>;
public function discombobulateRandomThingamajig():void {
thingamajigs[FP.rand(thingamajigs.length)].discombobulate();
}
}
public class MyEntity extends Entity {
override public function update():void {
if (condition_is_met) {
(world as MyWorld).discombobulateRandomThingamajig();
}
}
}
Secondly, if your entities are going to be accessing the cast world object a lot, it’s worthwhile to get them to keep their own cast reference to the world as a class member, like so:
public class MyEntity extends Entity {
private var myWorld:MyWorld;
override public function added():void {
myWorld = world as MyWorld;
}
override public function removed():void {
myWorld = null;
}
override public function update():void {
if (condition_is_met) {
myWorld.discombobulateRandomThingamajig();
}
}
}
Also, I wrote a post a little while ago about casting and what it means - perhaps you’d find it useful?
Wow. Thanks for the help, this is really informative as well as the link to that other post.
By the way I have another question. It seems that it really only work when I put it on the overriden added() method but it doesn’t when I put it on the constructor. Why is this?
Because in the constructor the entity hasn’t yet been added to the world.