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

2021/6/24

addObject in Actor class returns null

Shqxin Shqxin

2021/6/24

#
Player Constructor wrote...
public Player(){ HealthBar playerHealth = new HealthBar("player"); getWorld().addObject(playerHealth, 175,25); }
Health Constructor wrote...
public HealthBar(String name){ type = name; Img = name+"HealthBar01.png"; setImage(Img);
In the Player constructor, when the addObject is called, it returns a null pointer exception. However, when I do it in my World class, it works perfectly. Am I doing something wrong implementing the addObject method into my Actor class?
danpost danpost

2021/6/24

#
"public Player()" constructs a Player object. An actor cannot be placed in any world before it is constructed (it must obviously exist first). Therefore, "getWorld()" will always return a "null" value (no World object) in all Actor subclass constructors. Use (override) the addedToWorld method to add the health bar into the world.
Shqxin Shqxin

2021/6/27

#
it works! thanks!
You need to login to post a reply.