如何随机化两个浮点数之间的计时器持续时间

How To randomize timer duration between two floats

目前,这段代码生成我的预制件时只有 1 个浮点数,即 1 秒或 w.e。我想在最小浮动和最大浮动之间生成我的预制件,但不确定该怎么做,因为我是新手并且仍在学习 c# 和 unity。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Spawn : MonoBehaviour
{

    [SerializeField]
    public GameObject coin;

    [SerializeField]
    float fTimeIntervals;

    [SerializeField]
    Vector2 v2SpawnPosJitter;

    float fTimer = 0;

    public CurrencyManager cm;


    // Start is called before the first frame update
    void Start()
    {
        fTimer = fTimeIntervals;

    }

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

        fTimer -= Time.deltaTime;
        if (fTimer <= 0)
        {
            fTimer = fTimeIntervals;
            Vector2 v2SpawnPos = transform.position;
            v2SpawnPos += Vector2.right * v2SpawnPosJitter.x * (Random.value - 0.5f);
            v2SpawnPos += Vector2.up * v2SpawnPosJitter.y * (Random.value - 0.5f);
            GameObject cmscript = Instantiate(coin, v2SpawnPos, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
            cmscript.GetComponent<AutoDestroy>().CM = cm;
        }
    }


}

没看懂你的意思,你说的是定时器吗? 如果你想要一个介于 min/max 值之间的随机数,请使用 random.range https://docs.unity3d.com/ScriptReference/Random.Range.html

fTimeIntervals 字段拆分为 fMaxTimeInterval 字段和 fMinTimeInterval 字段,然后在重置计时器时使用 Random.Range 将其设置为这些间隔之间的值.您甚至可以在 StartUpdate 中创建一个 ResetTimer 方法来执行此操作,因此如果您更改操作方式,您只需更改一个地方:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Spawn : MonoBehaviour
{

    [SerializeField]
    public GameObject coin;

    [SerializeField]
    float fMinTimeInterval;

    [SerializeField]
    float fMaxTimeInterval;

    [SerializeField]
    Vector2 v2SpawnPosJitter;

    float fTimer = 0;

    public CurrencyManager cm;


    // Start is called before the first frame update
    void Start()
    {
        ResetTimer();
    }

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

        fTimer -= Time.deltaTime;
        if (fTimer <= 0)
        {
            ResetTimer();
            Vector2 v2SpawnPos = transform.position;
            v2SpawnPos += Vector2.right * v2SpawnPosJitter.x * (Random.value - 0.5f);
            v2SpawnPos += Vector2.up * v2SpawnPosJitter.y * (Random.value - 0.5f);
            GameObject cmscript = Instantiate(coin, v2SpawnPos, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
            cmscript.GetComponent<AutoDestroy>().CM = cm;
        }
    }

    void ResetTimer()
    {
        fTimer = Random.Range(fMinTimeInterval,fMaxTimeInterval);
    }
}