Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Best Method for Handling States

Discussion in 'Scripting' started by Tiernan98, Apr 7, 2018.

  1. Tiernan98

    Tiernan98

    Joined:
    Jul 11, 2017
    Posts:
    42
    Hey all,

    I was wondering if anyone would be willing to give me advice on how I'm structuring my project? Currently, I'm using singleton classes to handle the character's states (e.g. swimming, climbing) and setting a variable in the player controller called "currentState", which I use to call the state's update function within the player controller's update.

    I went about this method because it made sense to use singleton's for efficiency (not re-instantiating state objects constantly) and any code in a state that is not in use is not executed. My project can be found here: https://github.com/TiernanWatson/uraider.

    I just wanted to gather some feedback on this to see if anyone notices any major issues in my code design, or if there are things I should improve.
     
  2. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
    State machines.

    The style in the first reply there is one of the cleanest ways to implement a finite state machine. It doesn't really make sense to use singletons for this purpose.
     
  3. Tiernan98

    Tiernan98

    Joined:
    Jul 11, 2017
    Posts:
    42
    Thanks for the reply!

    This is very similar to what I have, except each state is a singleton. Why does it not make sense to use this design pattern? Does this not improve performance because the classes don't have to be re-instantiated each time?

    The only issue I currently see with it is if you wanted more than one player to use the same class.
     
  4. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
    It's just a pattern which is in common use, and it's probably commonly used for a reason. Listen to the wisdom of the crowd :)

    If you're using singletons for one type of state, you'd be duplicating code if you're also using non-singleton states for other things, like AI. So you'd have two types of state machine code unnecessarily. You only instantiate states once anyway - deallocating them between state changes would be silly. Why not use a type of state which works for everything?
     
    Tiernan98 likes this.
  5. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    Tiernan98 likes this.