我做了一个自定义类,我想创建一个movieclip的x实例。但以下不起作用:
package {
import flash.display.MovieClip;
public class CustomClass extends MovieClip {
public function CustomClass(amount:uint) {
var Collector:Array = new Array();
//Add and position Tiles to stage.
for (var i:uint = 1; i <= amount; i++){
var newMovieClip:MovieClip = new MovieClip;
newMovieClip.y = amount * 10;
Collector.push(newMovieClip);
}
addChild(Collector);
}
}
import flash.display.MovieClip;
public class CustomClass extends MovieClip {
public function CustomClass(amount:uint) {
var Collector:Array = new Array();
//Add and position Tiles to stage.
for (var i:uint = 1; i <= amount; i++){
var newMovieClip:MovieClip = new MovieClip;
newMovieClip.y = amount * 10;
Collector.push(newMovieClip);
}
addChild(Collector);
}
}
我想用
将它们放在时间轴上var customClass_mc:CustomClass = new CustomClass(10); addChild(customClass_mc); //try to trace the x position of one of the instances. trace(customClass_mc.Collector[5].x);
我一直收到错误:场景1,图层'第1层',第1帧,第5行1119:通过静态类型CustomClass的引用访问可能未定义的属性收集器。
答案 0 :(得分:2)
首先,您需要将Collector声明为public:
public var Collector:Array = new Array();
您的收集器是一个数组,而不是显示对象,因此无法将其添加到显示树中。相反,您可以将每个newMovieClip推送到Custom类的显示上,并将它们放在for循环中。然后你根本不需要收集器,因为你可以使用getChildAt()
:
trace(customClass_mc.getChildAt(5).x);
答案 1 :(得分:1)
我自己找到了另一个答案,我觉得它更好!
根本不需要容器。
使用以下
时package {
import flash.display.MovieClip;
public class CustomClass extends MovieClip {
public function CustomClass(amount:uint) {
//Add and position Tiles to stage.
for (var i:uint = 1; i <= amount; i++){
var newMovieClip:MovieClip = new MovieClip;
newMovieClip.y = amount * 10;
newMovieClip.name = "clip"+i;
addChild(newMovieClip);
}
}
}
}
不,我可以使用以下方式访问动画片段:
var customClass_mc:CustomClass = new CustomClass(10);
addChild(customClass_mc);
//try to trace the x position of the fifth instance.
trace(customClass_mc.getChildByName("child5").y);
答案 2 :(得分:0)
变量'Collector'仅在构造函数中以您拥有它的方式可用。必须公开收藏家才能从时间线外访问。最好的办法是制作一个公共getter方法来访问它。如下所示:
import flash.display.MovieClip;
public class CustomClass extends MovieClip {
private var Collector:Array = new Array();
public function get Collector():Array
{
return Collector;
}
public function CustomClass(amount:uint) {
//Add and position Tiles to stage.
for (var i:uint = 1; i <= amount; i++){
var newMovieClip:MovieClip = new MovieClip;
newMovieClip.y = amount * 10;
Collector.push(newMovieClip);
}
addChild(Collector);
}
}