Search Unity

Design pattern for managing state changes

Discussion in 'Scripting' started by Sendatsu_Yoshimitsu, Jun 29, 2015.

  1. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    I'm working on my combat system, and it's requiring a lot of character state rock-paper-scissors: movement can't occur if you're attacking, attacks can't occur if you're falling, and so forth.

    The brute force way to handle this, which is where I'm starting, is to give the player a boatload of bools: canMove, canAttack, canInteract, and so forth, and wrap the logic for handling each keypress in one big conditional loop, so every command reads like this:

    Code (csharp):
    1.  
    2. void MoveLeft(){
    3. if (canMove){
    4. //do movement stuff
    5. }
    6. }
    7.  
    Where this worries me is that managing the state of each bool is a very iffy proposition: right now I just have setters and getters for each state bool, and external functions toggle them as appropriate:

    Code (csharp):
    1.  
    2. void Attack(){
    3. if(canAttack){
    4. SetMovementPermission(false);
    5. //Call the requested animations and wait for them to finish, then...
    6. SetMovementPermission(true);
    7. }
    8. }
    9.  
    This is going to require tons of playtesting to guarantee that there is no combination of actions that can lead to a state's variable being set to False in a place that makes it unrecoverable.

    Is there an obvious design pattern I'm missing here, or is managing player state really as simple as curating a boatload of bools and making sure they don't get toggled at a bad time?
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
  3. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    Hmm alright, thank you. :)
     
  4. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    The design pattern you are looking for is called the strategy pattern. This is just one way of many to implement a finite state machine and is actually the pattern used by that wiki script.