This site requires JavaScript, please enable it in your browser!
Greenfoot back
SayMyName
SayMyName wrote ...

2012/6/10

How to clear an array of image

SayMyName SayMyName

2012/6/10

#
Hello guys, I have an explosion class with 15 image in it. How do I clear the array of images after it is used since simply removing the object doesn't solve the heap space error after using the explosion a few time.
public NukeExplosion ()
    {
        //initialize the array of blue explosion pictures
        nukeExplosion = new GreenfootImage[15];
        //filling the array with pictures
        for (int i = 1; i <= 15; i++)  
        {  
            nukeExplosion[i - 1] = new GreenfootImage ("nukeExplosion/" + i + ".png");  
        }  
    }

    /**
     * Act - do whatever the NukeExplosion wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        //add one to the act counter every act
        actCounter ++;
        //if statement that changes the picture every 5 act
        if (actCounter == 5)
        {
            //set act acounter to zero
            actCounter = 0;
            //set image of explosion
            setImage(nukeExplosion[curIndex]); 
            //if statement that adds to the curIndex if it isn't at 14
            if (!(curIndex == 14))
            {
                curIndex++;
            }
        }

        //if curIndex is 14 then it removes the explosion
        if (curIndex == 14)
        {
            SpaceWorld m = (SpaceWorld)getWorld();
            m.removeObject(this);
        }
    }    
Thank You
ttamasu ttamasu

2012/6/10

#
I assume there is multiple nuke explosions simultaneously and it is not set statically, it will just use a lot of heap space. Since you are using the garbage collector, you can tell java to tell java to try to release memory but there is no guarantee that it will do so. If I were you I would declare it as a static variable then all your explosions will use one set of images instead of multiple sets. (See the book example for asteroids). The nice thing about doing this is that the initialization routine is only done once and the data is not duplicated. It would go something like private static GreenfootImage nukeExplosion; ..... public static void initializeImages(){ if (nukeExplosion == null) { // images hasn't been initialized yet and only do once nukeExplosion = new GreenfootImage; for (int i = 1; i <= 15; i++) nukeExplosion = new GreenfootImage ("nukeExplosion/" + i + ".png"); } } public NukeExplosion(){ intializeImages(); }
You need to login to post a reply.