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

2016/4/15

How to access a variable of another Object if more than one Object exists

Cheiron3000 Cheiron3000

2016/4/15

#
Hi there How can I access a variable of an Object from an Actor if several of these Objects exist and they are'nt named. Is that even possible without a name? When a MiniDot is hit by a bullet, I need to check whether the bullet is from the enemy team or not, so I have to check the "team" variable from the bullet that hit the minidot in the MiniDot class. Here's my code: in the MiniDot class:
 Battlefield welt = (Battlefield) getWorld();
        if(isTouching(Bullet.class))
        {
            Actor bullet = getOneIntersectingObject(Bullet.class);
            boolean bt = welt.getBulletTeam(bullet);
            if(bt != team) beHit();
            getWorld().removeObject(bullet);
        }
so I'm trying to pass the found bullet to the World where it should have access to the Bullet class. in the Battlefield(that's my world) class:
public boolean getBulletTeam(Actor bullet){return bullet.getTeam();}
Of course there's a method called getTeam() in the Bullet class but it says it can't find the getTeam method. Can anyone help me to understand why?
danpost danpost

2016/4/16

#
The reason the method cannot be found is because the compiler does not know to look in the Bullet class for the field. You have the 'bullet' typed as an Actor object, not a Bullet object. You could change your method in the world class to this:
public Boolean getBulletTeam(Actor bullet){return ((Bullet)bullet).getTeam();}
Typed as a Bullet object the compiler will look in the Bullet classs for the method and find it. This being said, you should realize that you do not need the method in the Battlefield class at all. You can have the bullet typed properly in the MiniDot class just the same:
Bullet bullet = getOneIntersectingObject(Bullet.class);
if (bullet != null)
{
    if (bullet.getTeam() != team) beHit();
    getWorld().removeObject(bullet);
}
The above should be able to replace the entire code-set you gave above.
Cheiron3000 Cheiron3000

2016/4/16

#
Thanks danpost, now it works. But I had do put a "(Bullet)" before the getOneIntersectingObject method to ajust the types;P
danpost danpost

2016/4/16

#
Cheiron3000 wrote...
Thanks danpost, now it works. But I had do put a "(Bullet)" before the getOneIntersectingObject method to ajust the types;P
Apparently, I missed that -- sorry. Good job fixing it, however.
You need to login to post a reply.