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

2017/2/3

StackOverflow on vector of Actors

mehanix mehanix

2017/2/3

#
Hello! I've been trying to create a HUD for my game. I have 4 icons which represent the gems, from to 0 to 3. Each gem has a color. Based on the index given to the method, a different colored gem object is created.
public class GemIndicator extends HUD
{
    int cl;
    public GemIndicator(int colorIndex)
    {
        cl=colorIndex;
        switch(colorIndex)
        {
            case 0:
                {
                    GreenfootImage color = new GreenfootImage("gemRed.png");
                    setImage(color);
                    break;
                }
            case 1:
                {
                    GreenfootImage color = new GreenfootImage("gemBlue.png");
                    setImage(color);
                    break;
                }                
        
            case 2:
                {
                    GreenfootImage color = new GreenfootImage("gemGreen.png");
                    setImage(color);
                    break;
                }
            case 3:
                {
                    GreenfootImage color = new GreenfootImage("gemYellow.png");
                    setImage(color);
                    break;
                }                
            
            }
            getImage().setTransparency(120);
        }
    
    
    public void act() 
    {
        if(items.gems_taken[cl]==1)
            getImage().setTransparency(255);
    }    
}
public class HUD extends Actor
{
  GemIndicator[] gi = new GemIndicator[5];
    public HUD()
    {
    //    if(MyWorld.gamemode==1)
            {
                for(int i=0;i<4;i++)
                    {
                        gi[i]=new GemIndicator(i);
                        getWorld().addObject(gi[i],100,100);
                    }
            }
    }
}
I'm getting Stack Overflow on the HUD constructor(the line above the for is the marked one) How do I fix this? EDIT:I meant array, not vector, sorry.
danpost danpost

2017/2/4

#
Every time you create a GemIndicator object, because that class extends the HUD class, 'public HUD()' is executed and creates another one, which executes it again to produce another one, etc. Only the first iteration of the loop is ever started and an "infinite" number of constructor calls are being made. In other words, you should not be creating the objects from within its own superclass; they should be created from the world class.
mehanix mehanix

2017/2/4

#
Thanks! What you said makes sense and I've fixed the problem now.
You need to login to post a reply.