Collection to store all objects for easy retrieval

Hi!
I figured i’d go ahead and make a collection to store all my Room sprites in to get easy access to them instead of running a for loop for every function. I ran into a problem retrieving each room seen in the code posted below.

This is my RoomCollector class

class RoomCollector extends Sprite
{
public var _rooms: List;
public function new()
{
super();
_rooms = new List();
}

public function roomsExist(): Bool 
{
    return _rooms.isEmpty();
}
public function removeRoom(room: Room): Void 
{
    _rooms.remove(room);
}
public function fetchRoom() {
    for (room in _rooms) {
        return room;
    }
    return null;
}
public function addRoom(_room: Room, animated: Bool = false): Void 
{
    _rooms.push(_room);
    if (animated) { onCreateRoom(_room); }
}    
public function onCreateRoom(_room: Room): Void {
    Actuate.tween (_room, 1, { alpha: 1, scaleX: 2, scaleY: 2 }).ease (Quad.easeIn);
}

}

I soon realised that the following function

public function fetchRoom() {
    for (room in _rooms) {
        return room;
    }
    return null;
}

will always only return the first element of the list.
Is what i’m trying to achive a valid way of coding? Or do i still need to loop through the rooms elsewhere in the code to access all elements?

So what i would basically do is this:

_roomCollector = new RoomCollector();
_roomCollector.addRoom(new CommonRoom(_game), true);
addChild(_roomCollector.fetchRoom());
addChild(_roomCollector);

Which works great as long as there’s only 1 element inside the collection.

Using a list would mean that in the worst case scenario you would have to iterate over all of the rooms.

If you’re looking for a more performant lookup, you could always use a Map and key the rooms by some sort of identifier, such as the room’s name or some integer identifier.

I’m not too worried about performance since the user will not create more than let’s say… 20 rooms? So i’m more curious of what would be the correct way to code it to make it lesser painful handling all the room objects.

Well, you currently don’t have a way to fetch a specific room (aside from the first supplied room). So you’re going to have to have some sort of test to ensure you’re fetching the requested room.

So either use your list solution but check for equality on some value so that you’re returning the right room while you iterate through the list, or use something like a Map and key the rooms on some identifier.

I’ll have a look at Map :slight_smile: Never really had an oppertunity to use it before so could be fun! Thank you