How do you extract a Sprite back out of a ByteArray?

I should probably post this into some AS forums (and will do so later), but I had to get this out there quickly and it’s bugging the hell out of me:

In short, how do you extract a Sprite from a ByteArray? (or any kind of display object for that matter).

I can write the object just fine, and read it back into a variable, but I’ll be blown if I can then convert that back into what it was originally.

Here are my attempts so far:

[as]
var test:Sprite = new Sprite();
test.graphics.beginFill(0xff0000);
test.graphics.drawRect(0,0,64,64);
test.graphics.endFill();

//addChild(test); // to test, works fine

var b:ByteArray = new ByteArray();

trace(b.length);    //    0 bytes

b.writeObject(test);

trace(b.length);    //    754 bytes, so our Sprite is definitely in there

//    Reset the pointer
b.position = 0;

trace(b.position);    //    0 as I’d expect

var newTest:Sprite;
//newTest = b.readObject() as Sprite;    //    Ends up being null
//newTest = Sprite(b.readObject());    // Type Coercion failed error
//trace(newTest);
//addChild(newTest);    //    and kaboom, constant “Parameter child must be non-null.” errors 🙁

var take2:Object = b.readObject();
trace(take2);    // ok take2 contains an object, but how can I get the Sprite out of it?

trace(b.position);    //    754, so it has definitely read it all
[/as]

Ummm someone, please help? 🙂

Posted on February 28th 2009 at 11:47 am by .
View more posts in ActionScript3. Follow responses via the RSS 2.0 feed.


6 Responses

Leave a comment

Make yourself heard