Flash and Casting Arrays gives error?

Ok, so I’m using this to save out highscore data to SharedObjects. I’ve created a PlayerData class that looks like this:

class PlayerData
public var playerName:String = “John Doe”;
public var playerScore:Float = 123456;
public var playerCategory:String = “local”;

public function new(?name:String, ?score:Float, ?category:String)
	if (name != null) this.playerName = name;
	if (score != null)	this.playerScore = score;
	if (category != null) this.playerCategory = category;


And then I am accessing like this:

	var so:SharedObject = SharedObject.getLocal("localHighscores");
	var playerScores:Array<PlayerData> = so.data.localHighscores;

	for (playerScore in playerScores)

Which WORKS PERFECT for Windows and Android targets (at least), but it crashes on the FOR LOOP in Flash targets stating:

[Fault] exception, information=TypeError: Error #1034: Type Coercion failed: cannot convert Object@4b2fd01 to PlayerData.

I’ve tried adding in:
var playerScore:PlayerData;

But that didn’t seem to work… Any ideas how I can get my Flash target to work this way, I’d really hate to scrap this storage method because it’s really nice having everything compacted into a class…

Try using a typedef:

typedef PlayerData = {
    var playerName:String;
    var playerScore:Float;
    var playerCategory:String;

Can’t figure this out, perhaps it’s because it’s late…

If I create the typedef, then try to assign things to it, it doesn’t work…

pd : PlayerData;

pd.playerName = “test”;

gives me local variable pd used without being initialized.

If I try pd = new PlayerData(); then it complains about Can’t be constructed…

Oh, right, I should have mentioned the syntax for instantiating it. You have to define an anonymous structure.

var playerData:PlayerData = {

If the properties were all marked @:optional, then you could break this into multiple steps:

var playerData:PlayerData = {};
playerData.playerName = "John";
playerData.playerCategory = "tiger";

Problem is, then you’re allowed to skip the score, which probably isn’t something you want to allow.

1 Like

Worked like a charm! Weird thing is, it even recognized the data properly, which I was totally not expecting.

Thanks again!