0

我想训练一个 Unity ML 代理,并且在其功能的一部分,现在有一个编写为 Coroutine 的计时器。我觉得协程在训练中表现不佳,所以我想把它写成 void 而不是协程。协程看起来像这样:

        private IEnumerator AttackExecutionTimer(CharacterSettings opponent, ScriptableAttack attack)
        {
            float duration = attack.ExecutionTime;
            float normalizedTime = 0;
            while (normalizedTime <= duration)
            {
                normalizedTime += Time.fixedDeltaTime / duration;
                yield return null;
            }

            DoDamage(opponent, attack); //for testing, you can replace this with a log
            _isCompleted = true;
        }

这在正常播放模式下工作正常。但现在我想让它对我的代理培训无效,而且我尝试的每一次尝试都在短时间内造成这种损害,而不仅仅是一次。我想这是因为我不知道如何获得应该造成伤害的确切时刻。另外,首先我使用 Time.deltaTime,我只是将它切换到 Time.fixedDeltaTime 作为测试,以检查这是否会在训练中表现更好。

_isCompleted bool 在调用这个协程的方法中被检查和设置,如下所示:

            if (!_isCompleted)
            {
                return;
            }

            _isCompleted = false;
            //check some other conditions
            StartCoroutine(AttackExecutionTimer());
4

1 回答 1

1

您可以使用事件编程方法或回调

另一种选择是在 Unity中调用方法。

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    // Launches a projectile in 2 seconds

    Rigidbody projectile;

    void Start()
    {
        Invoke("LaunchProjectile", 2.0f);
    }

    void LaunchProjectile()
    {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5.0f;
    }
}
于 2021-02-01T13:22:20.197 回答