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

2021/5/23

How do I get the variable of an actor using an actor of the same class?

Simon567 Simon567

2021/5/23

#
I want to check if the variable f of the actor next to it (of the same class) equals 1 and if it does i want to change the variable f of the current actor to 1 aswell but I get the error "can not find symbol - variable f" and I dont know how to fix it. pls help
public class block extends Actor{
    int f = 0;
    public void act() {
        setRotation(90);
        bewegen();
    } 
    public void bewegen(){
        if(Greenfoot.isKeyDown("a")){
         if(getX() > 2 && getX() < 11){
           setLocation(getX()-1,getY());
         }
        }
        if(Greenfoot.isKeyDown("d")){
         if(getX() > 2 && getX() < 11){
           setLocation(getX()+1,getY());
         }
        }
        if(getY()<22 && getOneObjectAtOffset(0,1,block.class)==null){
            move(1);
        }
    }
    public void check(){
     Actor b1 = getOneObjectAtOffset(1, 0, block.class);
     if(b1 != null){
      if(b1.f == 1){
       f = 1; 
      }
     }
    }
}
danpost danpost

2021/5/23

#
The problem is how you declare b1 on line 23. You declare it as an Actor object. The compiler will not guess as to what type (subclass) of Actor it is and, therefore will not find f, since f is declared in the block class. You can fix this in either of the following ways: (A) change line 23 to:
block b1 = (block)getOneObjectAtOffsset(1, 0, block.class);
or (B) change line 25 to:
if (((block)b1).f == 1){
(A) allows the variable b1 to be of type block while (B) informs the compiler of its specific type when getting the field value. Actually (A) informs the compiler of its type when (potentially) getting the actor (which allows it to put it in a variable of that specific type).
Simon567 Simon567

2021/5/23

#
thank you very much you are a legend
You need to login to post a reply.