2013-07-12 127 views
0

基本上,正如標題所暗示的,我無法將我的數組保存到共享對象。無法將類對象保存到共享對象文件

我有一個包含不同的「兵」具有不同特徵的數組(健康,盔甲,武器,位置,精通,等級)等等等等,並想知道我怎麼會去保存它。當我重新載入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 (",,,,") 
     } 

回答

0

爲了保存自定義對象,你要麼必須使它的所有屬性的公共和方便,並沒有引用的DisplayObject,或實施IExternalizable和定義writeExternal()和方法。請注意,如果您的對象是從別處讀取的,則首先通過對其構造函數的零參數調用進行初始化,然後調用實例的。

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 
} 

所以,你的士兵,你只需要保存重要的數據,一旦你從共享對象加載你的士兵組重新創建一切。

+0

所以基本上你的意思是,我應該存儲在像健康每個單獨士兵的所有變量,然後重新創建一個新戰士類和共享對象的類士兵健康設爲savedHealth? –

+0

不完全。說你的士兵班有自己的變量「健康」。通過'writeInt()'調用將它寫入'writeExternal()'中,然後在'readInt()'調用中將其讀回到'readExternal()'中。與您想要保存的所有其他變量相同。請注意,順序很重要,因爲那些輸入和輸出實例不關心對象的數據完整性,所以您必須自己維護它。 – Vesper

+0

好的謝謝你的幫助:)我不會想出來的!乾杯:D –