Darren Loke
Darren Loke

Reputation: 23

How to create time intervals between states in an FSM

I would like to create a timer interval between the execution of a state in an FSM.

What I have at the moment is pretty basic as I'm still quite new to programming. It'd be great if you could keep any possible solutions to around a basic level.

public override void Execute()
{
    //Logic for Idle state
    if (dirRight)
        oFSM.transform.Translate(Vector2.right * speed * Time.deltaTime);
    else
        oFSM.transform.Translate(-Vector2.right * speed * Time.deltaTime);

    if (oFSM.transform.position.x >= 2.0f)
        dirRight = false;
    else if (oFSM.transform.position.x <= -2.0f)
        dirRight = true;
    //play animation

    //Transition out of Idle state
    //SUBJECT TO CHANGE
    float timer = 0f;
    timer += Time.time;
    if (timer >= 3f)
    {
        int rng = Random.Range(0, 5);
        if (rng >= 0 && rng <= 1)
        {
            timer = 0;
            oFSM.ChangeStateTo(FSM.States.AtkPatt1);
        }
        else if (rng >= 2 && rng <= 3)
        {
            timer = 0;
            oFSM.ChangeStateTo(FSM.States.AtkPatt2);
        }
        else if (rng >= 4 && rng <= 5)
        {
            timer = 0;
            oFSM.ChangeStateTo(FSM.States.AtkPatt3);
        }
    }
}

Upvotes: 2

Views: 160

Answers (1)

mayo
mayo

Reputation: 4075

You need to use Coroutines, and use the method WaitForSeconds.

Then you can do something like this:

private float timeToWait = 3f;
private bool keepExecuting = false;
private Coroutine executeCR;

public void CallerMethod()
{
    // If the Coroutine is != null, we will stop it.
    if(executeCR != null)
    {
        StopCoroutine(executeCR);
    }

    // Start Coroutine execution: 
    executeCR = StartCoroutine( ExecuteCR() );
}

public void StoperMethod()
{
    keepExecuting = false;
}

private IEnumerator ExecuteCR()
{
    keepExecuting = true;

    while (keepExecuting)
    {
        // do something
        yield return new WaitForSeconds(timeToWait);

        int rng = UnityEngine.Random.Range(0, 5);
        if (rng >= 0 && rng <= 1)
        {
            oFSM.ChangeStateTo(FSM.States.AtkPatt1);
        }
        else if (rng >= 2 && rng <= 3)
        {
            oFSM.ChangeStateTo(FSM.States.AtkPatt2);
        }
        else if (rng >= 4 && rng <= 5)
        {
            oFSM.ChangeStateTo(FSM.States.AtkPatt3);
        }

    }

    // All Coroutines should "return" (they use "yield") something
    yield return null;    
}

Upvotes: 3

Related Questions