Use Constants

Using constants for names and categories is very important

Why Use Constants

The Engine uses a lot of Strings to do its stuff. Objects in a Scene are identified by their Name and their Category. The Names and Categories are used everywhere and many times in the code, writing them every time is error-prone, so as a good practice, these Strings should be declared as constants. Also notice that Names and Categories should be unique, therefore having your constants in one place makes it easier to manage them.

//Example 01 : No constant, Bad
Object::Ptr myObject = getObjectManager()->findObject("player");
//Example 02 : Better
Object::Ptr myObject = getObjectManager()->findObject(ObjectPool.player);

How To Create A Constant Struct

You can organize all your constants in some C++ Struct variables, themselves being constant too. You have two ways of creating a constant struct has shown below

  • Method 01 : declare and instantiate you struct in one go
const struct 
    //put all your constants here
} MyFirstStruct;
  • Method 02 : declare and instantiate you struct in two time
struct _MySecondStruct
    //put all your constants here
const _MySecondStruct MySecondStruct;

The ConstantPool.h File

When you create a Full Project using CodeBlocks a file named ConstantPool.h will be generated along with your Project. You can use that file as a template for your constants. The most common category of constant are the following

  • Object Names
  • Object Categories
  • Sounds
  • Music
  • Game Screens
  • Player Actions
// Project MyScene
// Copyright (c) 2020 MyScene
namespace ng
	struct _ObjectPool
	    const std::string player			= "player";
	struct _CategoryPool
	    const std::string player             = "player";
	    const std::string ground             = "ground";
	    const std::string wall               = "wall";
	    const std::string power              = "power";
	    const std::string platform           = "platform";
	struct _SoundPool
	    const std::string sound01			= "sound01";
	struct _MusicPool
	    const std::string music01			= "music01";
	struct _ScreenPool
	    const std::string startScreen      	= "Start Screen";
	struct _PlayerActionPool
	    const std::string move_left          = "move_left";
	    const std::string move_right         = "move_right";
	    const std::string move_none          = "move_none";

	const _ObjectPool           ObjectPool;
	const _CategoryPool         CategoryPool;
	const _SoundPool     		SoundPool;
	const _MusicPool   			MusicPool;
	const _ScreenPool           ScreenPool;
	const _PlayerActionPool		PlayerActionPool;