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

2018/4/5

How to check if Actor still exists

skottc skottc

2018/4/5

#
In my Act method, I want to remove a bullet from the scene if it: (A) Reaches the edge of the screen or (B) Hits something. I have a method 'collision' which deals with, and removes the bullet and the object it collides with and an if-statement check to see if it's at world edge.
1
2
3
collision();
if (atWorldEdge())
        getWorld().removeObject(this);
My issue is if the object collides with something, it no longer exists, and cannot therefore be tested in 'atWorldEdge()'. I have tried encapsulating the if-statement in an if not null like below but to no avail.
1
2
3
if (!this.equals(null))
        if (atWorldEdge())
                getWorld().removeObject(this);
and
1
2
if (this != null && atWorldEdge())
                getWorld().removeObject(this);
Yehuda Yehuda

2018/4/5

#
If the problem is that you get a NullPointerException by atWorldEdge() (isAtEdge) because the Actor was removed from the World, then you can solve that problem by skipping the rest of the code in the method.
1
2
if (getWorld() == null) return;
// 'this' will never be null (I think)
skottc skottc

2018/4/5

#
Oh so you're saying this.getWorld() returns the world the object is located in? I've only got one world so I just assumed it just returned the world, irrespective of 'this'
Vercility Vercility

2018/4/5

#
'this' will always return a reference to whatever called it so it cant be null. include the atEdge check in your collision method as an if-else branch
You need to login to post a reply.