无法将类对象保存到SharedObject文件夹

时间:2013-07-12 08:56:57

标签: actionscript-3 loading save shared-objects

基本上如标题所示,我无法将数组保存到共享对象。

我有一个阵列,其中包含具有不同特征的不同“士兵”(健康,护甲,武器,位置,爆炸,等级)等等,并且想知道我将如何保存它。当我重新加载swf时,我得到了这个跟踪(“,,,”),但在重新加载之前,我得到了正确的数组读取。

如果有帮助,这是我的代码:

//Saving game
function saveGame(E:MouseEvent){    
var so:SharedObject = SharedObject.getLocal("saveFile"); //Instantiating the shared object

so.data.savedUnitArray = towerDefenceMain.unitArray;// is the array that stores the Soldiers

trace(so.data.savedUnitArray); //returns correct trace
so.flush();//Saving the operation
}


            //Loading the data back
        var so:SharedObject = SharedObject.getLocal("saveFile");

        if(so.data.savedUnitArray != undefined){
        unitArray = so.data.savedUnitArray;
        trace(unitArray); //returns (",,,,")
        }

1 个答案:

答案 0 :(得分:0)

为了保存自定义对象,您必须将其所有属性设为公共和可访问,并且不对DisplayObjects进行引用,或者实现IExternalizable并定义writeExternal()readExternal()方法。请注意,如果从其他地方读取对象,则首先通过对其构造函数的零参数调用对其进行初始化,然后调用实例的readExternal()

The manual on IExternalizable

一个例子:

public class Tower2 extends Obstacle implements gameRunnable,IExternalizable {
    // HUGE set of statistics skipped, all methods skipped
    public function writeExternal(output:IDataOutput):void {
    output.writeInt(gemType);
    output.writeInt(gemGrade);
    output.writeBoolean(affectsFlying); // as some gems might be elongated, saving this
    output.writeInt(_targetMode); // placeholder for targetting
    output.writeInt(kills);
    // hehe, what else to write in here? Everything else is derivable
}

public function readExternal(input:IDataInput):void {
    var gt:int = input.readInt();
    var gg:int = input.readInt();
    MakeGem(gt, gg); // this is the function that initializes everything that's the tower
    raised = true; // will place manually if ever
    affectsFlying = input.readBoolean();
    gt = input.readInt();
    SetTargetting(gt);
    kills = input.readInt(); // kills
    updateDamage(); // this updates damage respective to kills counter
}

因此,对于你的士兵,你只需要保存基本数据,并在从共享对象加载一组士兵后重新创建其他所有数据。