Search code examples
actionscript-3

Actionscript 3 - Stage not recognising added child when changing index


Firstly, for clarity, I am 6-months new to ActionScript 3.

Under the current project of a small game, the player sprite's bitmap is changed every frame to whatever image is necessary. During this same process, this sprite's (as a child of the stage) index is updated to ensure it remains at the top of every other image.

(This code is refined to the bare necessities of this process to avoid confusion)

function playerFrame (newBitmap):void {
  player.removeChild(prevBitmap);
  player.addChild(newBitmap);
  prevBitmap = newBitmap;
  stage.setChildIndex(player, stage.numChildren - 1); //<-- targeted line
}
function tick (event:Event):void {
  playerFrame(bitmap) //<-- whatever the player bitmap needs to be changed to
}
stage.addEventListener(Event.ENTER_FRAME, tick);

I had left this project for a week and when I returned - after no changes to the program were made - this targeted line presented a mysterious error:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

(being the player not a child of the stage)

The mystery not the error itself, but rather the cause of the error: Within the program, the player sprite is added as a child to the stage, and never touched again.

After not finding a solution to this error (either in the code or online) I restored the program to a previous save, proving to not yield the same problem. However later, after adding a tracer (trace() function) for debugging, it appeared once more. It seems to be a commonly caused error without the common causes.

Strange question, I know, but really bugging me. Anyone experienced such occurrences?


Solution

  • You should instead do like this: player.bitmap.bitmapData=newBitmapData; and drop all the shufflings of addChild. A Bitmap object is a wrapper for displaying a BitmapData, and thus can be directed to display any bitmapdata. And since the display list is not altered this way, you don't need to reorder it in the slightest (in response to this set of actions, at least).