0
\$\begingroup\$

What is the difference between the constructor of a BasicGameState and the init method? It appears that they are both called at the same time when the BasicGameState is registered in StateBasedGame, so what makes them different?

A follow up question to this is how do I run a method only when a state becomes active? Initially I thought the init method was only called when a new state becomes active, but this is not true. Note that I'd like to call this method only once at the beginning of the new state, so putting it in the update method seems like the wrong place.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I don't use this library myself, but I guess the best way to get your answers is by looking at the source code of slick, which can be found on bitbucket. Here is a link to the states package. \$\endgroup\$ – Terje Feb 21 '14 at 8:55
2
\$\begingroup\$

This really boils down to coding conventions. The general idea is that the constructor's primary purpose is to create the object itself. However that object is a dumb object and shouldn't actually do anything until specifically told to do so.

The init() method, also known as create(), initialize(), etc... is the used to actually run code on the object.

In most cases, you're going to use your object as soon as it's created. Therefore you might not notice the need to separate these concerns in many cases. However there may be cases where you want some object, but you don't need it doing anything just yet.

\$\endgroup\$
1
\$\begingroup\$

I agree with what Terje said, as you might want to go into the documentation and poke around until you find what you're looking for, but here's a quick thing for you.

Whenever a game class offers a different choice to use rather than a constructor, it is almost always best to use that. LibGDX has a similar method called create(), which is custom-tailored so that the game objects are spawned in the correct manner. While there's nothing wrong with using constructor's, if a framework provides you with that alternative, use it. I would still recommend looking into it, however.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.