AS3 Accessing Parent Class Variables from Child

I am trying to assign a parent variable from a parent child

//Parent
public class Main extends Sprite
    {   
    public var selectedSquare:Sprite;

    public function Main()
        {
        //inits and adds new Square child class to display list
        }
...

-------

//Child
public function dragSquare(evt:MouseEvent):void
    {
    Sprite(parent).selectedSquare = this; //evil doesn't work!
    parent.addChild(this);
    this.startDrag();
    }

      

I am getting this error, but I am throwing the parent from displayObjectContainer to Sprite, so I have no idea why it is not working.

1119: Accessing the possibly undefined selectedSquare property via a link with the static type flash.display :. Sprite

+2


source to share


2 answers


You have to serve the parent as the main and not the sprite, since the Sprite will not have references to "selectedSquare". If Main were to extend the MovieClip, this would not be a problem, since the MovieClips can have dynamically generated links.

Proposed modification of the child function:



public function dragSquare(evt:MouseEvent):void
{
    (parent as Main).selectedSquare = this;
    parent.addChild(this);
    this.startDrag();
}

      

+4


source


Another reason this might not work is if you are trying to use the property parent

right before adding the child to the parent display list.

Sprite(parent).selectedSquare = this;
parent.addChild(this);

      

This second line worries me. In this code, the current object ( this

) must already be added as a child to the parent object ( Main

) for the first line to work properly. So either the current object is not yet a child of the parent, in which case you need to revisit your code.

Or the second line is not needed (since it is this

already a child Main

, so this.parent

either just parent

works as expected).



I believe your code is probably well set up. You just don't need this second line as it is completely redundant.

I hope this helps! Let me know if you would like me to clarify something.

(This is, of course, assuming you still don't know all of this and do some crazy, arcane, weird, over-challenging magic addChild

. You can never tell wizards!)

+1


source







All Articles