2014-10-30 143 views
0

我似乎與我的庫存系統有差錯。As3錯誤:錯誤#1009:無法訪問空對象引用的屬性或方法

這是我的課:

package 
{ 
    import flash.display.*; 

    public class InventoryDemo extends MovieClip 
    { 
     var inventory:Inventory; 

     public function InventoryDemo() 
     { 
      inventory = new Inventory(this); 
      inventory.makeInventoryItems([d1,d2]); 
     } 
    } 
} 

我已經放置在第二個關鍵幀D1和D2的對象。

這是子類:

package 
{ 
    import flash.display.*; 
    import flash.events.*; 

    public class Inventory 
    { 
     var itemsInInventory:Array; 
     var inventorySprite:Sprite; 

     public function Inventory(parentMC:MovieClip) 
     { 
      itemsInInventory = new Array ; 
      inventorySprite = new Sprite ; 
      inventorySprite.x = 50; 
      inventorySprite.y = 360; 
      parentMC.addChild(inventorySprite); 

     } 
     function makeInventoryItems(arrayOfItems:Array) 
     { 
      for (var i:int = 0; i < arrayOfItems.length; i++) 
      { 
       arrayOfItems[i].addEventListener(MouseEvent.CLICK,getItem); 
       arrayOfItems[i].buttonMode = true; 
      } 
     } 

     function getItem(e:Event) 
     { 
      var item:MovieClip = MovieClip(e.currentTarget); 
      itemsInInventory.push(item); 
      inventorySprite.addChild(item); 
      item.x = itemsInInventory.length - 1 * 40; 
      item.y = 0; 
      item.removeEventListener(MouseEvent.CLICK,getItem); 
      item.addEventListener(MouseEvent.CLICK,useItem); 
     } 

     function useItem(e:Event) 
     { 
      var item:MovieClip = MovieClip(e.currentTarget); 
      trace(("Use Item:" + item.name)); 
     } 
    } 
} 

代碼的工作,當我嘗試在只有D1和D2在舞臺上的黑項目。任何人都可以幫我解決這個問題嗎?

+0

對於我們來說,知道錯誤在哪裏出現也是很有用的。 – AndySavage 2014-10-30 16:11:57

+0

當我做了調試其說:無法訪問空對象引用的屬性或方法。在庫存/ makeInventoryItems() – Pickles 2014-10-30 17:20:05

回答

0

你的錯誤提示,D1和D2不是你叫

inventory.makeInventoryItems([d1,d2]); 

你認爲你已經創建了D1和D2在第二個關鍵幀時創建的,但如果InventoryDe​​mo是你的DocumentClass,那麼它將在您到達第二個關鍵幀之前運行。

因此,如果您想使用d1和d2,您需要將它們移動到第一幀,或者您需要在電影的第二幀出現之前不要嘗試使用它們。

如果你想保持D1和D2第二幀上,那麼你就需要採取呼出的構造,進入你的第二幀上調用一個新的功能:

public function InventoryDemo() 
{ 
    //Do nothing here 
    //inventory = new Inventory(this); 
    //inventory.makeInventoryItems([d1,d2]); 
} 

public function initialiseInventory():void 
{ 
    //Initialise you inventory here. 
    inventory = new Inventory(this); 
    inventory.makeInventoryItems([d1,d2]); 
} 

然後在你的時間線的第二幀調用函數:

initialiseInventory(); 
stop(); 
+0

OMG非常感謝你,我可以問另一個問題...?,我如何使用一個項目...像D1是一個鑰匙打開一個門 – Pickles 2014-10-30 18:45:10

+0

恐怕你的問題是真的不夠具體。如果你有一個特定的問題,你找不到答案,然後將其作爲一個新問題發佈,然後我們可以爲你回答。 – 2014-10-31 08:33:52