我想在FSM中执行状态之间创建一个计时器间隔。
我现在所拥有的是非常基本的,因为我还是很喜欢编程。如果你能在基本水平上保持任何可能的解决方案,那就太好了。
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);
}
}
}
答案 0 :(得分:3)
您需要使用Coroutines,并使用方法WaitForSeconds。
然后你可以这样做:
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;
}