Libgdx游戏内存不足和崩溃

时间:2018-01-17 16:43:34

标签: android memory-management libgdx out-of-memory

嘿,我做了一个在屏幕上移动的小鱼游戏,用户需要击中它们并杀死它们,2-3分钟后应用程序才完全终止,我无法弄清楚原因,我只是创建一次对象并在屏幕上移动它们。

我得到的信息是

I/art: Background partial concurrent mark sweep GC freed 4771(2029KB) AllocSpace objects, 230(4MB) LOS objects, 39% free, 9MB/16MB, paused 3.054ms total 173.279ms

这里有一些代码: 创建图像数组:

fishes = new Image[30];
    directionX = new int[30];
    directionY = new int[30];
    speed = new int[30];
    dead = new boolean[30];
    deadTimer = new int[30];


    Random random = new Random();
   Drawable drawable = new TextureRegionDrawable(new TextureRegion(new Texture("idag.png")));

    for(int i =0;i<fishes.length;i++)
    {
        int xlocation = random.nextInt(2);
        int ylocation = random.nextInt(2);
        dead[i] = false;
        deadTimer[i] = 0;

        fishes[i] = new Image(drawable);
        fishes[i].setWidth(character.getWidth()/3);
        fishes[i].setHeight(character.getWidth()/3);
        GenerateLocation(i);

        stage.addActor(fishes[i]);
    }

这是每个鱼位死亡时的产生

 public void GenerateLocation(int i) {
     random = new Random();

        int xlocation = random.nextInt(2);
        int ylocation = random.nextInt(2);
        if (xlocation == 0) {
            fishes[i].setX(-random.nextInt(8000));
            directionX[i] = 1;

        } else {
            fishes[i].setX(width + random.nextInt(8000));
            directionX[i] = -1;
        }

        if (ylocation == 0) {
            fishes[i].setY(random.nextInt((int) (height/2)));
            directionY[i] = 1;
        } else {


            fishes[i].setY(height-random.nextInt((int) (height/2)));
            directionY[i] = -1;
        }

        if (directionX[i] == 1 && directionY[i] == 1) {
            drawable = new TextureRegionDrawable(new TextureRegion(new Texture("idag-45.png")));
            fishes[i].setDrawable(drawable);
            //fishes[i].setRotation(-45);

        } else if (directionX[i] == 1 && directionY[i] == -1) {
            drawable = new TextureRegionDrawable(new TextureRegion(new Texture("idag-135.png")));
            fishes[i].setDrawable(drawable);
        } else if (directionX[i] == -1 && directionY[i] == 1) {
            drawable = new TextureRegionDrawable(new TextureRegion(new Texture("idag45.png")));
            fishes[i].setDrawable(drawable);
        } else if (directionX[i] == -1 && directionY[i] == -1) {
            drawable = new TextureRegionDrawable(new TextureRegion(new Texture("idag135.png")));
            fishes[i].setDrawable(drawable);
        }
        speed[i] = random.nextInt(levelSpeed) + 1;

}

任何人都可以帮助我吗?我真的不知道我还能做些什么来使这项工作。

谢谢!

1 个答案:

答案 0 :(得分:1)

我看到很多new Texture调用,所以你生成了很多对象。实现Disposable的LibGDX中的任何内容都必须在您失去对它的引用之前调用dispose()。这是因为Disposable将数据保存在本机内存中,因此GC不会清理它。

此外,反复加载相同的图像而不是重复使用相同的Texture实例是浪费时间。你的每条鱼都有另一份相同的图像副本加载到内存中。