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

2020/6/25

"incompatible types: greenfoot.Actor cannot be converted to Figur" Error appearing when trying to use Figur figur = getOneIntersectingObject(Figur.class)

Lorenz123 Lorenz123

2020/6/25

#
Hello, my problem is named in the title. I unterstand what the message wants to tell me but i don't know a way around it. I hope somebody can help me. Here's the method with the error:
public void powerUp()
    {
         Figur figur = getOneIntersectingObject(Figur.class);
         if(figur != null && figur.yRichtung == 1)
         {
             if(figur.status == "babyFigur")
             {
                 World dieseWelt = getWorld();
                 RoterPilz roterPilz = new RoterPilz();
                 dieseWelt.addObject(roterPilz, this.getX(), this.getY()-24);
                 AktiviertesFragezeichen aktiviertesFragezeichen = new AktiviertesFragezeichen();
                 dieseWelt.addObject(aktiviertesFragezeichen, 0, 0);
                 dieseWelt.removeObject(this);
             }
         }
    }
Lorenz123 Lorenz123

2020/6/25

#
Just realized the 2nd if is pointless should have used another &&. So here's the code again.
public void powerUp()
    {
         Figur figur = getOneIntersectingObject(Figur.class);
         if(figur != null && figur.yRichtung == 1 && figur.status == "babyFigur")
         {
             World dieseWelt = getWorld();
             RoterPilz roterPilz = new RoterPilz();
             dieseWelt.addObject(roterPilz, this.getX(), this.getY()-24);
             AktiviertesFragezeichen aktiviertesFragezeichen = new AktiviertesFragezeichen();
             dieseWelt.addObject(aktiviertesFragezeichen, 0, 0);
             dieseWelt.removeObject(this);
         }
    }
Super_Hippo Super_Hippo

2020/6/25

#
Try this:
Figur figur = (Figur) getOneIntersectingObject(Figur.class);
The method returns an Actor object. Since it is certainly a Figur object, you can simply cast it with the (Figur) part.
Lorenz123 Lorenz123

2020/6/25

#
thanks! It worked.
danpost danpost

2020/6/25

#
Line 3: getOneIntersectingObject returns an object (or 'null') typed as an Actor object. The compiler will not assume it is a Figur object and "blindly" place the object in a variable that is to specifically reference a Figur object. You must tell the compiler that it, if it does exist, will indeed be of type Figur before it will place the reference in the variable. Hence the line Super_Hippo suggested.
You need to login to post a reply.