user24028
user24028

Reputation: 39

How to deal with two game modes in the same script?

If for instance I have a game which consists of just a single scene, and in that scene I make the user chose between the normal play mode or the tutorial play mode. The game has 4 different objects: a ball, 4 squares and a squarecontroller. In the tutorial mode i want to provide the user with a pointing arrow while pausing the game and continue after the user pressed the object being pointed at. Should I make a script for the normal mode and another one for the tutorial mode, make one script and check if a tutorial boolean is true or false in every function (boolean should be true if user pressed the tutorial button) or do some kind of preprocessing?

In the squarescript for example:

void OnCollisionEnter2D () {
 if (isTutorial) {
    PauseGame();
    arrow.position = GetRelativePosition();
    arrow.setActive(true);
 } else {
  if (canCollide) {
    score++;
  } else {
    GameOver();
   }
 }

In the ballscript:

void OnMouseDown () {
   if (!isTutorial) {
      return;
   }

   ResumeGame();
}

Upvotes: 0

Views: 79

Answers (2)

CaTs
CaTs

Reputation: 1323

By structuring these behaviours inside if statements, it makes the code hard to understand and work with. Imagine what this will look like if you decide you want one of the squares to increase the players score AND show a tutorial arrow.

Split the behaviours into separate objects. For the square it could be something like a TutorialCollisionHandler, ScoreCollisionHandlerand HazardCollisionHandler. Then you can create different squares simply by changing which collision handlers are added to them, you don't even need to write any code!

Now depending on which mode the user picks, you can just use a different mix of squares. The same principle can be used with other tutorial or game specific behaviour.

Upvotes: 1

Oscar Lundberg
Oscar Lundberg

Reputation: 433

We know nothing of your game so it's hard to answer. But as a rule of thumb: The less you have to type, the better. Also consider what will happen if you need to add new functionality to the game, will you have to go back and change tons in your code? If so, you are most likely not writing good code.

As an attempt to give a concrete answer I'd say you should make an inheritance, create a class Level and make sub classes Tutorial and FreePlay or similar, that inherits from Level.

Then you can add all "general" functionality in the base class and the specific things goes in the sub classes

Upvotes: 3

Related Questions