PDA

View Full Version : Object management and references


jorrit5477
10-17-2007, 01:37 PM
Hi,

I am currently working on a game in which I have a central place for creating Entities, called EntityManager. This singleton class maintains a map (associative array) of references to all created Entities. These are created using the method
private var mEntities:Array;

public function createEntity(name:String):Entity
{
if (name && !mEntities[name])
{
var ent:Entity = new Entity(name);
mEntities[name] = ent;
return ent;
}
return null; // For clearance, would be better to throw an exception
}
It would make sense to me when I have a create operation, I als have a destroy operation, which would look like
public function destroyEntity(name:String):void
{
if (name)
{
var ent:Entity = mEntities[name];
delete mEntities[name]; // Clear the place in the map
// Make all references to the Entity invalid, but how???
}
}

How could I make all references to an object invalid? Calling a sort of destructor in which I call delete this, doesn't do the trick.

Can anybody point me the right direction?

Cheers!

panel
10-17-2007, 03:23 PM
I doubt it is possible.

ryryguy
10-17-2007, 04:11 PM
Yeah, as far as I know, there's no way to "back trace" references to a given object, so you can't really brute force it at Entity delete time. You have to prepare the ground in advance.

You could certainly code "double ended" references, where each time something stores a reference to an Entity, it also registers with the Entity, so when the Entity wants to go away, it calls back and says basically, "let me go!" Or maybe better, define an event that the Entity can dispatch to indicate that it wants to be deleted. Anything else that grabs a reference to the Entity also adds a listener for that event.

I recommend this series of articles about resource management in AS3: http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html. In fact, in part 3 there is a "WeakReference" class that you could use to get what you are wanting.

jorrit5477
10-17-2007, 04:45 PM
After reading the article of Skinner I assume this is not possible indeed. This is in some way rather unfortunate, since this implies proper management of objects is rather difficult (I sometimes prefer a null pointer exception which I can track back and repair, instead of difficult to find behaviour due to references which do exist).

I dive into the weakreferences, but I don't know if that would be really needed. Thank you!

Jim Freer
10-17-2007, 05:10 PM
Although I haven’t been writing games I guess I can imagine why an object might be referenced in more than one entity. In general a lot of different persistent references to the same object would represent a weaker architecture even if it is your only choice.

However regardless of how many references there are, you could raise an event in your object to inform interested containers that it would like to be deleted.

Jim
http://freerpad.blogspot.com/