如何从最小值和当前值之间的range属性中获取随机数?

问题描述 投票:-2回答:2

最小为20,最大为300。例如,如果在检查器中滑块的当前值为120,则选择20到120之间的一个随机数,如果在运行游戏之前或在游戏运行时将值更改为77,则下一个随机数应为20至77之间。

我希望每次NPC每X随机秒执行一次操作。例如,在运行游戏后,如果随机数是20或90,则在20秒或90秒后,npc将执行某些操作。然后是下一个随机数(如果是199),则在199秒后,npc将执行相同的操作(某事),依此类推。

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class RandomTester : MonoBehaviour
{
    public List<GameObject> npcs;
    [Range(20, 300)]
    public int timeVisit = 20;
    public string nextVisitTime;

    // Start is called before the first frame update
    void Start()
    {
        npcs = GameObject.FindGameObjectsWithTag("Npc").ToList();


    }

    // Update is called once per frame
    void Update()
    {

    }
}
c# unity3d
2个回答
0
投票

要生成20至300之间的X个随机数并将它们添加到列表中,请执行以下操作:

Random r = new Random();
List<int> rands = new List<int>();
for (int i = 0; i < X; i++)
{
    rands.Add(r.Next(20, 300));
}

0
投票

也许我没有很好地解释它。

这是我想要的并且正在工作。我正在从范围属性的滑块的最小值和当前值之间获取随机数,这是检查器中的滑块。

然后,我将在每次更改检查器中的值时,选择一个随机数,将启动协程,等待完成时,该协程将等待随机抽取的秒数,以完成某些工作。

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class RandomTester : MonoBehaviour
{
    public List<GameObject> npcs;
    [Range(20, 300)]
    public int timeVisit = 20;
    public string nextVisitTime;

    private int oldtimevisit;

    // Start is called before the first frame update
    void Start()
    {
        npcs = GameObject.FindGameObjectsWithTag("Npc").ToList();

        oldtimevisit = timeVisit;
    }

    // Update is called once per frame
    void Update()
    {
        if(timeVisit != oldtimevisit)
        {
            StopAllCoroutines();
            Debug.Log(Random.Range(20,timeVisit));

            var timetowait = Random.Range(20, timeVisit);
            StartCoroutine(Waiting(timetowait));
        }

        oldtimevisit = timeVisit;
    }

    IEnumerator Waiting(int waitingtime)
    {
        yield return new WaitForSeconds(waitingtime);

        DoSomethingWithNpcs();
    }

    private void DoSomethingWithNpcs()
    {

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.