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

2016/3/9

Make an if-statement execute once

Bassusour Bassusour

2016/3/9

#
I want to execute this if-statement once, when true. public void nd_missil() { Player_1 a = (Player_1) getWorld().getObjects(Player_1.class).get(0); if (a != null && a.get_FD_spist() == 1) { getWorld().addObject (new ND(), getX(), getY()); } } I've read a little about counters, bot I do not know how to use it.
davmac davmac

2016/3/9

#
Please use code tags when you post code. What you need, I think, is a boolean instance variable to track whether the condition has already been true.
boolean is_done = false;

public void nd_missil()
{
    Player_1 a = (Player_1) getWorld().getObjects(Player_1.class).get(0);
    if (a != null && a.get_FD_spist() == 1 && ! is_done) {
        getWorld().addObject (new ND(), getX(), getY());
        isDone = true;
    }
} 
Actually, the "a != null" check is ineffective. getObjects() returns a list which will not contain null items. You probably should instead check that the list is not empty (before you retrieve the first item with the call to "get(0)").
Bassusour Bassusour

2016/3/9

#
Thanks for the reply, it helped me :)
You need to login to post a reply.