【问题标题】:As3 Error: Error #1009: Cannot access a property or method of a null object referenceAs3 错误:错误 #1009:无法访问空对象引用的属性或方法
【发布时间】:2014-10-31 02:13:17
【问题描述】:

我的库存系统似乎有问题。

这是我的课:

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 的黑色项目中尝试时,该代码有效。谁能帮我解决这个问题?

【问题讨论】:

  • 知道错误发生在您的代码的哪个位置对我们很有用。
  • 当我进行调试时,它说:无法访问空对象引用的属性或方法。在库存/makeInventoryItems()

标签: actionscript-3 class


【解决方案1】:

您的错误表明在您调用时未创建 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();

【讨论】:

  • 我的天啊,非常感谢,我能再问一个问题吗...?,我如何使用一个项目...比如 d1 是打开门的钥匙
  • 恐怕您的问题还不够具体。如果您有某个特定问题无法找到答案,请将其作为新问题发布,然后我们可以为您解答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
相关资源
最近更新 更多