NavMeshAgent.SetDestination后不会自动寻路问题

2022/6/25 23:33:28

本文主要是介绍NavMeshAgent.SetDestination后不会自动寻路问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

# 下面的代码是想实现点击鼠标左键,寻路到指定的位置;但是运行后,并不会寻路,而是立即打印了end

void Update()
{
    if (Input.GetMouseButtonUp(1))
    {
        _navMeshAgent.enabled = true;
        _navMeshAgent.SetDestination(_targetPos);
    }

    if (_navMeshAgent.enabled)
    {
        if (_navMeshAgent.remainingDistance <= 0)
        {
            Debug.Log($"end");
            _navMeshAgent.enabled = false;
        }
    }
}

 

# 经过各种排查之后,最终确定是SetDestination后,会先计算如何寻路,至少要到下一帧才进行真正的寻路,所以方法1是SetDestination后return等待一帧

void Update()
{
    if (Input.GetMouseButtonUp(1))
    {
        _navMeshAgent.enabled = true;
        _navMeshAgent.SetDestination(_targetPos);
        return;
    }

    if (_navMeshAgent.enabled)
    {
        if (_navMeshAgent.remainingDistance <= 0)
        {
            Debug.Log($"end");
            _navMeshAgent.enabled = false;
        }
    }
}

# 或者方法2判断下是否在计算寻路数据中

void Update()
{
    if (Input.GetMouseButtonUp(1))
    {
        _navMeshAgent.enabled = true
        _navMeshAgent.SetDestination(_targetPos)
    }

    if (_navMeshAgent.enabled && !_navMeshAgent.pathPending)
    {
        if (_navMeshAgent.remainingDistance <= 0)
        {
            Debug.Log($"end");
            _navMeshAgent.enabled = false;
        }
    }
}

 



这篇关于NavMeshAgent.SetDestination后不会自动寻路问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程