0

Is it possible to reference an object using a variable value?

For example, I have a function that is supposed to hide an image and add that image to an inventory list when the item is clicked.
All the image info is stored in an object (name, imgSource, visible, x, y);

I was thinking I could do something like this:

<fx:Script>
    <![CDATA[
        public var item:Object = new Object();

        // name, imgSource, xPos, yPos, visible
        [Bindable]
        public var knife:ItemInfo = new ItemInfo('knife','knife.png',50,50,true);

        public function addItem(evnt:MouseEvent):void
        {
            // I want "item" to be equal to the object "knife"
            item = evnt.currentTarget.name;
            item.visible = false;
            inventory.addItem(item.name);
        }
    ]]>
</fx:Script>

<s:Image source="{knife.source}" name="knife" 
         x="{knife.xPos}" y="{knife.yPos}" 
         visible="{knife.visible}"
         click="addItem(event);" />

I want "item" to stand for knife so that I could change knife.visible, knife.xPos, ect.
Is that possible, or is there a better way to do this?

Thanks!

2 Answers 2

1

Why does item have to be an Object ? Why cannot it be of type ItemInfo ?

Also item = evnt.currentTarget should work if you want item to reference the knife image that was clicked.

Update

ToolInfo ? or ItemInfo ?

Anyway evnt.currentTarget is of type object. Try casting it to type ItemInfo.

evnt.currentTarget as ItemInfo

Sign up to request clarification or add additional context in comments.

2 Comments

If i make "item" a type ItemInfo, I get this error: 1118: Implicit coercion of a value with static type Object to a possibly unrelated type components:ToolInfo.
that didn't work either error: cannot access property "visible", but I guess I did figure out a different way to do it. Thanks for the help anyways
0

The easiest way to change the values of the object on click is just to pass the object itself into the addItem() function. The problem with this is that I have to preselect which variable goes into the function at what time, but for this purpose it works great.

<fx:Script>
<![CDATA[
    public var item:Object = new Object();

    // name, imgSource, xPos, yPos, visible
    [Bindable]
    public var knife:ItemInfo = new ItemInfo('knife','knife.png',50,50,true);

    public function addItem(item:ItemInfo):void
    {
        item.visible = false;
        inventory.addItem(item.name);
    }
    ]]>
</fx:Script>

<s:Image source="{knife.source}" name="knife" 
     x="{knife.xPos}" y="{knife.yPos}" 
     visible="{knife.visible}"
     click="addItem(knife);" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.