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



目前,这段代码生成我的预制件,只有 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;
        }
    }

}

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);
    }
}

不太明白你的意思,你是说计时器吗?如果您想要一个介于最小值/最大值之间的随机数,请使用 random.rangehttps://docs.unity3d.com/ScriptReference/Random.Range.html

最新更新