我正在尝试从父母的孩子那里分配父母的变量
//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();
}
我收到此错误,但我正在将displayObjectContainer中的父级转换为Sprite,所以我不知道它为什么不起作用。
1119:访问可能未定义 物业选择广场通过 静态类型的引用 flash.display使用:精灵
答案 0 :(得分:4)
您应该将父级转换为Main而不是Sprite,因为Sprite不会引用任何“selectedSquare”。如果Main要扩展MovieClip,这不会有问题,因为MovieClip可以有动态创建的引用。
对儿童功能的拟议修改:
public function dragSquare(evt:MouseEvent):void
{
(parent as Main).selectedSquare = this;
parent.addChild(this);
this.startDrag();
}
答案 1 :(得分:1)
这可能不起作用的另一个原因是您在将子项添加到父级的显示列表之前尝试使用parent
属性。
Sprite(parent).selectedSquare = this;
parent.addChild(this);
第二行让我担心。在此代码中,当前对象(this
)必须已作为子对象添加到父对象(Main
),以使第一行正常工作。因此,当前对象还不是父对象的子对象,在这种情况下,您需要修改代码。
或者,第二行是不必要的(因为this
已经是Main
的孩子了,这就是为什么this.parent
或parent
按预期工作的原因。“ / p>
但是,我相信你的代码可能设置得很好。你不需要第二行,因为它完全是多余的。
我希望有所帮助!如果您要我澄清任何内容,请告诉我。
(当然,这是假设你还不知道所有这一切,并且没有做多余的addChild
电话那种疯狂,神秘,奇怪的魔法。你永远无法告诉魔术师!)