【问题标题】:Unable to save class objects to a SharedObject FIle无法将类对象保存到 SharedObject 文件
【发布时间】:2013-07-10 18:30:54
【问题描述】:

基本上正如标题所暗示的那样,我无法将我的数组保存到共享对象中。

我有一个数组,其中包含具有不同特征(生命值、护甲、武器、位置、经验、等级)等的不同“士兵”,我想知道如何保存它。当我重新加载 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 (",,,,")
        }

【问题讨论】:

    标签: actionscript-3 loading save shared-objects


    【解决方案1】:

    为了保存自定义对象,您要么必须将其所有属性公开且可访问,并且不引用 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
    }
    

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

    【讨论】:

    • 所以基本上你的意思是我应该将所有变量存储在每个单独的士兵中,比如 Health,然后重新创建一个新的士兵类并将类士兵的健康设置为 Shared Object 中的 savedHealth?
    • 不完全是。假设您的士兵类有自己的变量“健康”。您通过writeInt() 调用将其写入writeExternal(),然后在readInt() 调用中将其读回readExternal()。您要保存的所有其他变量也是如此。请注意,顺序很重要,因为这些输入和输出实例不关心对象的数据完整性,您必须自己维护它。
    • 好的,感谢您的帮助 :) 我想不通!干杯:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2016-09-09
    • 2016-08-15
    • 2013-12-27
    相关资源
    最近更新 更多