开发者_JAVA百科may i ask how can i cast a object to another type? in AS3 i tried putting (objectType) infront of the variable but it doesnt work, below i have added objects of fishes into the child, and i am getting the fishes back out when mouse down is triggered, and then calling the fishes what to do. however i cant call the method of the custom class fish because it is a displayobject.
private function onMouseDownTriggered(e:MouseEvent):void
{
var food:Food = new Food(this, _stageRef.mouseX, _stageRef.mouseY);
for (var i :int = 0; i < this.numChildren; i++)
{
var fish : fish= this.getChildByName("fish" + i);
fish.getFood(food);
}
}
A cast in AS3 can be achieved as follows:
var fish:Fish = Fish(this.getChildByName("fish" + i));
or
var fish:Fish = this.getChildByName("fish" + i) as Fish
Keep in mind though that the first cast notation is more restrictive and will effectively cause runtime exceptions when cast restrictions have not been met.
The second notation is much looser and will not cause any runtime exceptions. This can be quite error prone and should be handled with care.
Cheers
精彩评论