我的目标是将矩形创建为具有舞台大小的MovieClip,但Flash给了我这个错误:
1120:访问未定义的属性阶段。 (在第6,7,14行)
我的代码:
package {
import flash.display.MovieClip;
public class main {
var mc_background:MovieClip = new MovieClip();
var stageW:Number = stage.stageWidth;
var stageH:Number = stage.stageHeight;
public function main() {
drawBackground();
}
public function drawBackground():void {
mc_background.beginFill(0xFF00CC);
mc_background.graphics.drawRect(0,0,stageW,stageH);
mc_background.graphics.endFill();
stage.addChild(mc_background);
}
}
}
答案 0 :(得分:4)
我有一个类似的问题,问题是,舞台还没有真正设置好,所以你需要等待从中获取数据或其中的内容。只需添加:
protected function addedToStageHandler(event:Event):void
{
//do stuff
}
protected funcion init():void
{
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
//more stuff
}
希望有所帮助
答案 1 :(得分:1)
在将对象添加到舞台或舞台上的其他对象之前,不会定义对象的stage
属性。
在创建类实例时调用类的构造函数,即在将实例添加到舞台之前。因此,您无法访问从构造函数调用的代码中的阶段,或者在定义实例变量stageW
和stageH
时。
要在将对象添加到舞台后立即访问舞台属性,请允许该对象处理ADDED_TO_STAGE事件:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class main
{
var mc_background:MovieClip = new MovieClip();
public function main()
{
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
// Generally good practice to remove this listener from the object now because it stops addedToStageHandler from being called again if the object is removed and added back to the stage or display list.
removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
drawBackground();
}
private function drawBackground():void {
mc_background.beginFill(0xFF00CC);
mc_background.graphics.drawRect(0,0,stage.stageWidth, stage.stageHeight);
mc_background.graphics.endFill();
addChild(mc_background);
}
}
}