Unity IEnumerator,正在等待,但不再完全执行调用的函数



我正在编写一个带有一些逻辑的游戏,该逻辑记录了玩家的行为,然后在相同的时间以相同的顺序重播它们,但以后会涉及其他影响。

到目前为止,我的代码可以正常工作,它可以按照我的需要完美记录,然后完美地回放序列,但问题是时间问题。

举一个简单的例子。如果字符是从 A -> B> C 走,但在 B 处等待 x 时间,则代码很容易遍历路径,但在给定时间内不会在 B 处停止。

所以我写了几个函数,我认为可以处理这个问题,正如你在这里看到的。

private IEnumerator followSequence()
{
// Loop through each action steps in sequence.
foreach (Action step in sequence)
{
//Check if the action time is less than the current clock time.
Debug.Log("Step.tick: " + step.tick + " || Clock.tick: " + clock.getTick());
if (clock.getTick() < step.tick)
{
//If so wait out the difference to resync the action.
yield return new WaitForSeconds(step.tick - clock.getTick());                
}
// Carry out the step.
play(step);
}
yield break;
}
private void play(Action step)
{
Debug.Log(step.type);
// Set up a followpath script
FollowPath follow = (player.GetComponent<FollowPath>() ? player.GetComponent<FollowPath>() : player.AddComponent<FollowPath>());
// Tell the follow path script that object is not a guard.
follow.isGuard = false;
// Create a new point object on the map
Transform aPoint = (Transform)Instantiate(PathPoint, step.point, Quaternion.identity);
path.points.Add(aPoint);
// Initiate movement.
follow.Path = path;
follow.TravelPath();
// Check if action is an objective.
if (step.type == Action.Type.Action)
{
step.actions.OnClick();
}        
}

现在,如果我注释掉第一个函数中的*yield return new WaitForSeconds()*部分,代码将按预期工作,并完成序列中的步骤,只是没有达到给定的时间。

当相同的代码没有被注释掉时,那么计时就会完美地工作,第二个*Debug.log("step.type")*在正确的时间被调用,但是字符不再移动,即*follow.TravelPath()*似乎永远不会被执行。

我尝试将第二个函数设为 IEnmerator 并屈服于它。我尝试了一个自定义的wait()函数。我尝试过屈服于 TravelPath() 函数。

有没有人有更多的想法,或者我可以在哪里尝试解决这个问题?

编辑:

根据请求调用 followSequence() 的代码:

private void playActions()
{
// Reset player immediately to the starting position
player.transform.position = sequence[0].point;
// Stop the character and freeze the scene when alarm sounds!.
player.GetComponent<IncrementController>().freeze();
player.GetComponent<IncrementController>().enabled = false;
// Restart the clock and scene.
clock.Restart();
sceneManager.restart();
// Activate guard and remove sphere.
guard.SetActive(true);
guardShere.SetActive(false);
// Stop recording;
recording = false;
line.SetActive(false);
// Start playback sequence.
StartCoroutine(followSequence());
}

行为符合预期,在你执行的行上,yield return上下文的执行暂停,直到你在枚举器上执行MoveNext()(这显然从未发生过),枚举器由followSequence返回。

但据我从评论中看到,您只想等待几秒钟进行重新同步,因此您根本不需要返回。在您的情况下,如果您只想跳过一些时间,我看不出您可能需要WaitForSeconds的可枚举的任何理由。不知道您如何调用函数和WaitForSeconds的实现,我建议您将其返回类型更改为void

private void followSequence()
{
// Loop through each action steps in sequence.
foreach (Action step in sequence)
{
//Check if the action time is less than the current clock time.
Debug.Log("Step.tick: " + step.tick + " || Clock.tick: " + clock.getTick());
if (clock.getTick() < step.tick)
{
//If so wait out the difference to resync the action.
new WaitForSeconds(step.tick - clock.getTick());                
}
// Carry out the step.
play(step);
}
}

最新更新