简体   繁体   中英

AS3 Dynamically naming object properties

I'm working on a sort of Entity Component System in AS3. Within my EntityManager class I have a function called createEntity. It takes in an array of strings that then becomes the entitiy's components.

public function createEntity(newComponents:Array):void
    {
        var newEntity:Entity = new Entity();
        var obj:Object = new Object();
        obj.id = newEntity.id;

        // This is what I would like to do.
        var newComponentName:String;
        for (var i:int = 0; i < newComponents.length; i++)
        {
            newComponentName = newComponents[i];
            obj.newComponentName = createComponent(newComponents[i]);
        }

        trace(obj.Health); // result = undefined

        /* This was my previous setup. This way makes it really hard for my systems to access the components.
        var components:Array = [];
        for (var i:int = 0; i < newComponents.length; i++)
        {
            components.push(createComponent(newComponents[i]));
        }
        obj.components = components;
        */
    }

Furthermore, the systems access the entities by an ID. Within entityManager there is a getEntityByID function. I would like to be able to (from the HealthSystem class) call upon an entity's health component like this: (simplified a bit)

getEntityByID(testID).Health

When using the createEntity function, all of the components have different names, so I would like to name them dynamically. If anyone has any experience with this, help would be appreciated! Thanks!

omg. I love how I spend forever typing out my questions, then the answer hits me seconds after posting it.

var newComponentName:String;
        for (var i:int = 0; i < newComponents.length; i++)
        {
            newComponentName = newComponents[i];
            obj[newComponentName] = createComponent(newComponents[i]);
        }

        trace(obj.Health);

This totally works! Thanks anyways. I would still be happy if anyone has more info on the subject or on Entity Component System architecture in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM