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

2016/12/1

Calling an specific object from a class

AlphaCookie AlphaCookie

2016/12/1

#
I am trying to use a public String variable from an object in my world. There are other objects of the same class on the world, so i used Object obj=getOneObjectAtOffset to determine what actor i want to refer to. My problem is now, that obj.name can not be found, even though the object has a public string variable "name". What do i do wrong?
danpost danpost

2016/12/1

#
AlphaCookie wrote...
I am trying to use a public String variable from an object in my world. There are other objects of the same class on the world, so i used Object obj=getOneObjectAtOffset to determine what actor i want to refer to. My problem is now, that obj.name can not be found, even though the object has a public string variable "name".
The variable reference 'obj' is declared to hold an Object type object. So, the compiler will look no further than the Object class for the 'name' field -- and will not find it. If you use:
1
Actor obj = getOneObjectAtOffset(0, 0, ActorSubclassName.class);
(which is okay because the 'getOneObjectAtOffset' method returns an object of type Actor), the compiler will look as far as the Actor class for the 'name' field (and still not find it). To have the compiler look in the class that the field is actually located, it needs to look like this:
1
ActorSubclassName obj = (ActorSubclassName)getOneObjectAtOffset(dx, dy, ActorSubclassName.class);
The Actor object returned by the method is typecast as an ActorSubclassName object and set to a reference variable that is declared to hold an ActorSubclassName object. Now 'name', of the ActorSubclassName object, will be found.
You need to login to post a reply.