Search Unity

State Machine for skills

Discussion in 'Scripting' started by Viole, Jul 27, 2017.

  1. Viole

    Viole

    Joined:
    Dec 29, 2015
    Posts:
    38
    Hi, I'm working on skills in a game. For example I have a dash skill, which dashes and then goes on a cooldown.
    To do that I use a state machine like this one from the first reply:
    https://forum.unity3d.com/threads/c-proper-state-machine.380612/

    My question is:

    - do I need a state machine for every skill I can use? I wanted to use only one for every character, but what if one skill goes on a cooldown? Then I would have to wait for it to use different skill.

    - maybe there's a better way of handling skills? Is it effective way of handling skills?
     
  2. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,038
    You'd only need two states per skill if doing it the state machine way, so in that respect it's fine. Though skills on cooldown are much simpler to code by checking if the last use was far enough in the past.

    But there's another way to do it: Use Mecanim. It's already a state machine! Fire an event when the cooldown finishes on whatever indicator you have for the skill being in cooldown, which sets a boolean for readiness. Done :)
     
  3. Viole

    Viole

    Joined:
    Dec 29, 2015
    Posts:
    38
    I'll try mecanim in a second, but just to be clear: would I need a separate state machine (not state) for every skill if I was to do it my way?
    So would I need a separate state machine for dash, for jump, for skill3, etc?

    And mecanim is basically Animator, right? So I'd have to use parameters. So it probably has to look through all parameters each time. Wouldn't it be slow for more states?
     
  4. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,038
    Yeah, you'd need to attach one to each. Each skill needs a few properties for timings, like activation time, cooldown and duration, plus references to graphics/animations and a virtual Execute() method. Technically you only need idle and ready states (even if the animation has more states), so not many state classes per skill. Best of all, the idle class can be designed so that you only need one shared across all skills.

    If you're using Mecanim's Animator at the core of your timing and events, this is a starting point:
    https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html

    Don't worry about parameter efficiency :)

    You set things up so you get a trigger when the state changes from playing the cooldown animation to the idle/ready state. You only run it every <cooldown> units of time, not 60 times per second. You're unlikely to have more than 10-12 cooldowns visible, and if you have a computer which can't handle that number of cooldowns I suggest unplugging it, write "JUDAS" on it in crayon and catapult it into a wall.

    This post was edited down from a rambling mess. Void where prohibited.