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

2012/11/3

How to check which world actor is in?

zhuvell zhuvell

2012/11/3

#
In the actors act() method, I am trying to make it's actions differ, depending on the world it's in.
if (Greenfoot.mouseClicked(this))
        {
         
            if (this.getWorld() == Room11)
            {
            //further actions}
       
    }    
I know why this doesn't work but how do I only return the name of the world, so I can compare? I only want the actor to perform certain actions if it's on a particular world.
erdelf erdelf

2012/11/3

#
this should work
try
        {
            World world = (Room11) getWorld();
            //further actions
        }catch (ClassCastException x) {}   
zhuvell zhuvell

2012/11/3

#
Thank you so much, I was afraid I would have to make new objects for each world or something xD
iau iau

2012/11/3

#
Rather than having to deal with the ClassCastException when the world is not a Room11, you could just say:
if (this.getWorld().getClass() == Room11.class) {
    // further actions
}
danpost danpost

2012/11/4

#
I believe that
if (getWorld() instanceof Room11)
would also work.
iau iau

2012/11/5

#
Yes it would. The only difference is that instanceof is true if the World is of class Room11 or any subclass of Room11., for example, if you have "class Room11a extends Room11". Which may or may not be what you want.
You need to login to post a reply.