开发者

Accessing properties via a String in AS3

I have an engine I created a while back that loads objects into a container based on XML data. A really quick example of the XML would be like this:

<level>
    <object cname="enemies.Robot">
        <pos x="200" y="400" layer="mobiles" />
    </object>
    <object cname="Player">
        <pos x="12" y="89" layer="mobiles" />
    </object>
</level>

I have a class Environment that has a method loadLevel(data:XML) which I parse the XML through, then the function runs through the XML finding all object nodes and uses getDefinitionByName to determine which Object I want to create based on object.@cname.

From here, I have to manually define each property based on the XML like so;

obj.x = xml.pos.@x;
obj.y = xml.pos.@y;

etc.

I was wondering if there's an inbuilt method for setting a property based on a String. By this I mean something like so:

var mc:MovieClip = new MovieClip();
mc.someInbuiltFunctionThatSetsAProperty("alpha", 0.5);

This way I could change my XML to be more like so:

<object cname="Player">
    <props>
        <x>200</x>
        <y>221</y>
        <alpha>7834</alpha>

        <health>Something</health>
        <power>3</power>
    </props>
</obje开发者_JAVA百科ct>

And iterate through all the children of props to set all of my properties on the fly.

I know if I create an Object and set properties within it like so:

var obj:Object = 
{
    var1: "hello",
    var2: "there",
    name: "marty"
};

That you can then iterate through names/values using the for(String in Object) loop like this:

var i:String;
for(i in obj)
{
    trace(i + ": " + obj[i]);
}

/**
 * Output:
 * var1: hello
 * var2: there
 * name: marty
 */

Is there maybe something even similar to that?

Surely there's a way, as here's an example of identifying a property using a String:

var ar:Array = [new MovieClip(), new MovieClip()];
ar.sortOn("alpha", Array.ASCENDING);

So just to make my question more to-the-point: I want to be able to get and set properties that I can identify using a String.


Why not using ["string property"] notation :

var mc:MovieClip=new MovieClip()
mc["alpha"] = 0.5            // setter
var alpha:Number=mc["alpha"] // getter


I'm not quite clear on what it is you're looking for exactly, but I have a general sense of what you're getting at and have a few suggestions for you. First, have a look at the documentation for the Object class in the AS3 Language Reference. Look specifically at the propertyIsEnumerable() and setPropertyIsEnumerable() methods. I think that's what you're asking about.

If not, you might want to look into the behavior of dynamic classes, which let you add variables to an object on the fly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜