- Home /
Question by
SpokenPI · Dec 18, 2017 at 05:18 PM ·
programmingcharacter controllercharacter movementenumstate-machine
Character Controller with multiple state machines
Hello. I am fairly inexperienced at coding and I am currently trying to code a character controller. What I currently am using is multiple enums as state machines and switching to the different enums depending on input. I have included a copy of my code template but removed most of the actual code to make it easier to read.
I just want some advice if this solution is viable. It currently works as I intend it too but being inexperienced I am not sure if I will run into issues or if I am being inefficient. Any advice would be appreciated.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class OS_PlayerMovement : MonoBehaviour
{
public enum CharacterState {Idle, Walk, Run, Crouch, Roll, Slide, Falling}
public CharacterState characterState;
public enum CombatState {Standby, CombatIdle, Attack, Defend}
public CombatState combatState;
//variables here
void Awake ()
{
characterState = CharacterState.Idle;
combatState = CombatState.Standby;
}
void Start ()
{
StartCoroutine("Movement");
}
IEnumerator Movement ()
{
while(true)
{
switch(characterState)
{
case CharacterState.Idle:
Idle();
break;
case CharacterState.Walk:
Walk();
break;
case CharacterState.Run:
Run();
break;
case CharacterState.Falling:
Fall();
break;
}
yield return null;
}
}
IEnumerator Combat ()
{
while(true)
{
switch(combatState)
{
case CombatState.Standby:
break;
case CombatState.Attack:
Attack();
break;
}
yield return null;
}
}
void LateUpdate ()
{
//Check for inputs. move character and switch states accordingly
//stop and start coroutines depending on input
}
void Idle ()
{
//play Idle code and Idle animation
}
void Attack ()
{
//Attack Code
}
void Fall ()
{
//apply gravity and fall animation, check amount of time falling and apply damage
}
void Walk ()
{
//movement code
}
void Run ()
{
//running code
}
void CharacterRotation ()
{
//rotate character
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612144819im_/https://answers.unity.com/themes/thub/images/avi.jpg)