First of all, good job. Your diagram looks fine so far. What is missing is what is supposed to happen when the player enters, for example, State 2.
In your code, you already have a bool named “enemy”, which is fine. However, what can the player do to defeat the enemy? Does he need a specific item? Can he use his fists? Does the enemy have health?
In your diagram, you already have defined the Player and the Enemy stats. For simplicity, you could create a bunch of variables for the player, and a bunch of variables for the “current” enemy in AdventureGame.
In each State, you need to declare a health variable for the enemy which represents the max health. Do not change the value during runtime. This is important. Otherwise, your values will get overridden while playing your game. When you start your game next time, you will not get the original values again. Your enemy will remain “dead” forever.
When a State with enemy == true
gets “loaded” in the AdventureGame instance, you assign the health value of the enemy to the enemyHealth
variable in the AdventureGame instance.
You also have to keep track of the defeated enemies. That’s simple.
// Instead of 20, use the number of states you have
HashSet<int> defeatedEnemyID = new HashSet<int>(20);
int enemyHealth = 0;
void DoSomething()
{
if (state.HasEnemy() && enemyHealth == 0)
{
defeatedEnemyID.Add(state.GetInstanceID());
}
}
void SomeOtherMethod()
{
// You can proceed to the next state if the enemy is dead or if there isn't an enemy
if (!enemy || defeatedEnemyID.Contains(state.GetInstanceID())
{
// proceed with the next state
}
else
{
// allow player to attack
}
}
While you are on it, you could also define actual game states in your game with an enum. That’ll help you control the user input / user interface. For example:
enum GameState
{
Inventory,
LoadEnemy,
Attack,
SelectState,
Lose
}
GameState gameState = GameState.SelectState;
void Update()
{
if (gameState == GameState.SelectState)
{
if (Input.GetKeyDown(KeyCode.A)) { // code }
}
else if (gameState == GameState.Lose)
{
if (Input.GetKeyDown(KeyCode.Enter)) { // code for restarting the game }
}
}
All you need to do is to wire up your logic with enums and if-statements. With the GameState value, you can define states in which something specific is supposed to happen. For example:
if the State has an enemy => gameState = GameState.LoadEnemy => “load” the enemy values => gameState = GameState.Attack
Without the enums, the player could “attack” even if there isn’t anything. He could reload the game even though he has not lost or won. And so on.
Does that make sense?