Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question How to combine the single responsibility principle with a finite state machine?

Discussion in 'Scripting' started by Slater7, Sep 3, 2020.

  1. Slater7

    Slater7

    Joined:
    Oct 10, 2018
    Posts:
    11
    I'm working on a game where I have some characters to choose from and they each behave differently.
    I followed the Single-Responsibility-Principle and split every behavior like "Crouch", "Jump", "Movement", etc. in separate scripts so that I can attach them to the Player who should be able to do them.
    For example PlayerOne can jump and move but can't crouch. So I attach the "Jump.cs" and "Movement.cs", but not the "Crouch.cs" script.
    So long it's working perfectly fine.

    Now I want to implement a state machine for each player to let them behave different when they are in another state like "InAir-STATE", "OnGround-STATE" or whatever, you get the idea.
    For example when in "InAir-STATE" then "Movement.cs" controls should behave differently than in "OnGround-STATE".

    Example player prefab:
    PlayerOneComponents.png

    I read about using enums as a simplified state machine, but don't know how to implement them in a architecture like mine and also that they don't scale well.
    So my question is how to implement a finite state machine (or maybe a better alternative) in a game like this?
    Thanks!