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

2013/5/31

actor not in world

welleid welleid

2013/5/31

#
Hey guys, i have s problem. I try to add some objects in the creation progress of my world : IG. I use a for loop, like that in the "public IG()"
for(int j = 0; j < 2; j++) //Boucles d'ajout des blocs
        {
            for(int i=0; i < 6; i++)
            {
                Bloc bloc = new Bloc(Greenfoot.getRandomNumber(10) );
                addObject(bloc, 100 + (i*121), 70 + (j*100)); 
            }
        }
Then, in my Bloc class :
public Bloc(int param)
    {
        if(param <= 5)
        {
            setImage("bloc.png");
        }
        
        else if(param > 5)
        {
            setImage("blochelice.png");
            getWorld().addObject(new Helice(), getX(), getY() ); //this part gets highlighted
        }
    }
But i get an actor not in world error message from java console. I think it's probably easy, but brain.class is running out of memory. And i have to put the code in thoses classes, like the code of setting the blocs picture must be in the bloc class. Thanks a lot !
danpost danpost

2013/6/1

#
Yeah. An object needs to be created before it is put into a world (the constructor must have finished executing and then the object must be placed into a world). You cannot use 'getWorld' in a constructor (it will return 'null') and you cannot use 'getX()' or 'getY()' (you will get IllegalStateException -- actor not in world). You have two options: (1) put the random 'param' value in a local field and add the 'Helice' object from the world class; or (2) add the 'Helice' object into the world after the Bloc object is placed into a world.
welleid welleid

2013/6/1

#
ok so i tried something like this :
public int typeBloc; 
    
    public Bloc(int param)
    {
        if(param <= 5)
        {
            setImage("bloc.png");
            typeBloc = 0;
        }
        
        else if(param > 5)
        {
            setImage("blochelice.png");
            typeBloc = 1;
        }
    }
    
    public void act() 
    {
       addHelice();
    }    
    
    public void addHelice() 
    {
        if(typeBloc == 1)
        {
            getWorld().addObject(new Helice(), getX(), getY() );
            typeBloc = 2; 
        }
    }
In the Bloc.class. Now I can compile it, but the Helice appear after I hit the run button. I'd like it to be on screen just after i compiled it.
Gevater_Tod4711 Gevater_Tod4711

2013/6/1

#
If you call the addHelice method not from the act method but when the actor is added to the world it should work:
public void addedToWorld(World world) {
    addHelice();
}
Then you don't need to call this method from the act method anymore.
welleid welleid

2013/6/1

#
Yup thanks mate, didnt thinkl about that ! Thanks a lot !
You need to login to post a reply.