Search Unity

Question Looking for tips on checking bools across multiple scripts

Discussion in 'Scripting' started by lemmons, Jan 21, 2021.

  1. lemmons

    lemmons

    Joined:
    Jun 20, 2016
    Posts:
    68
    My code is functional, but I'm looking to see if I can refactor it to be cleaner, possibly more performant, and pick up some tips and best practices along the way!

    I've built a state machine using enums and switches to determine the state (ex: moving, attacking, idling, etc.) of the unit. When the state changes it fires off a `OnStateChanged` action and all the listener scripts respond appropriately.

    However, there are certain requirements I have to check for before changing states. Things like "am I currently in the middle of an attack animation?" or "am I disabled by some status effect?". For those specific examples I've got bools in each respective script for "isAttacking" and "isDisabled" and my state machine is dropping into a coroutine where it waits for both bools to be false before effectively changing its state.

    But what if I want to add more prerequisites to changing state in the future? I've not got to add more conditionals to my state machine's `RequestStateChange` coroutine and more checks and variables across other scripts. There's got to be a better way—right?

    I've dabbled with creating a Func in my state machine script that returns a bool and all the listener scripts will run their bool checks when called. However, this caused me to create additional coroutines in those scripts to wait until the bool turned false which seemed worse than my initial solution.

    I also played around with creating a `Queue` for my states and holding onto them until the bool check passed, but even then I was relying heavily on that bool check coroutine.

    Thank you in advance for any guidance!