首页 > 解决方案 > 如何在两个浮点数之间随机化计时器持续时间

问题描述

目前,此代码仅以 1 个浮点数(即 1 秒)生成我的预制件,或者我们想在最小浮点数和最大浮点数之间生成我的预制件,但不知道该怎么做,因为我是新手,仍在学习 c# 和统一。

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


}

标签: c#unity3dcloneinstantiation

解决方案


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


推荐阅读