我在AS3制作游戏。
我有一个班级“Dechets”,其中3个movieClips随机出现。
public var _classes:Array = new Array(coco1, coco2, coco3,coco4);
public var _cocoMovieClips:Array = new Array();
public function cocoAppear(event : TimerEvent):void{
var cocoMc:DisplayObject = new _classes[Math.floor(Math.random() * _classes.length)]();
_cocoMovieClips.push(cocoMc);
stageRef.addChild(cocoMc);
cocoMc.addEventListener(MouseEvent.CLICK, removeCoco, false, 0, true);
trace( getOnStage() );
}
public function removeCoco(event:MouseEvent):void{
var cocoMc:DisplayObject = event.target as DisplayObject;
if (!cocoMc) return; // typecast failed
cocoMc.parent.removeChild(cocoMc);
trace(cocoMc);
}
那么,你知道我怎么能把
if(cocoMc == "coco4"){
doSomething();
}
感谢您的帮助
答案 0 :(得分:2)
如果您只想知道阵列中哪个在舞台上:
function getOnStage():DisplayObject
{
for(var i:int = 0; i < _classes.length; i++)
{
if(_classes[i] is DisplayObject)
{
var o:DisplayObject = _classes[i] as DisplayObject;
if(stage.contains(o)) return o;
}
}
return null;
}
用过:
trace( getOnStage() );
答案 1 :(得分:0)
问题是什么?
你想知道这个对象在舞台上吗?当你从舞台上删除它们时,可能会尝试从数组中删除这些项目,或者如果你想保留第一个包含所有项目的数组,可以为此创建第二个数组。
例如:
public function removeCoco(event:MouseEvent):void
{
var cocoMc:DisplayObject = event.target as DisplayObject;
if (!cocoMc) return;
cocoMc.parent.removeChild(cocoMc);
// get the index of the cocoMc in the array
var i:int = _cocoMovieClips.indexOf( cocoMc );
// remove the cocoMc from the array
if( i != -1 ) _cocoMovieClips.splice( i, 1 );
// if you want to check the type of your mc
if( cocoMc is coco4 ) doSomething();
else if( cocoMc is coco3 ) doSomethingElse();
}
之后你可以跟踪你的数组:
trace( _cocoMovieClips );
如果您有很多要测试的类型,可以替换:
// if you want to check the type of your mc
if( cocoMc is coco4 ) doSomething();
else if( cocoMc is coco3 ) doSomethingElse();
由:
var classe:String = getQualifiedClassName( cocoMc);
classe = classe.substring( classe.lastIndexOf(':')+1 );
switch( classe )
{
case 'coco1': doSomething1(); break;
case 'coco2': doSomething2(); break;
case 'coco3': doSomething3(); break;
case 'coco4': doSomething4(); break;
}