Random.Range 总是返回相同的值

时间:2021-06-11 00:13:59

标签: c# unity3d

我正在尝试在 Unity C# 中对旅行推销员进行一个小型模拟,但我无法解决这个问题,我的代码看起来正确但 start 和 nxtCity 向量总是导致相同的位置,我真的不明白为什么,你们中有人能帮忙吗?

城市是城市总数

positions 是从城市生成器中获取的城市数组 这两个值在统一编辑器中是正确的

代码如下:


void Start()
{
    positions = cam.GetComponent<citiesGene>().positions;
    cities = cam.GetComponent<citiesGene>().cities;
    Debug.Log(rand);
    start = positions[Random.Range(0, cities)];
    transform.position = start;
    StartCoroutine(ChooseCity());
}

IEnumerator ChooseCity()
{
    
    while (true)
    {
        nxtCity = positions[Random.Range(0, cities)];
        arrive = false;
        StartCoroutine(GoTo(nxtCity));
        while (arrive == false)
        {
            yield return new WaitForFixedUpdate();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

Unity 的 Random.Range with (int, int) 重载 (NOT float, float) 生成范围 [min; max),max 是独占的,因此如果您调用 var randomInt = Random.Range(0, 1),结果将始终为 0。var randomInt = Random.Range(0, 2) 将是 0 或 1,例如

答案 1 :(得分:0)

谢谢大家我解决了这个问题,它在另一个函数中