首页 > 解决方案 > 如何在 Unity 中使用 C# 生成随机浮点数(Unity 拒绝大多数其他建议的答案)?

问题描述

希望生成一个随机浮点数,但 random.range 不起作用,因为“您需要指定System.Random()UnityEngine.Random()”。如图所示使用 System.Random 时,它说“不可调用的成员“随机”不能用作方法”,即使它应该是。UnityEngine.Random()是一个奇怪的设备,它会弄乱我稍后要考虑的其他随机值。真正厌倦了统一,程序使简单的编码变得如此困难。

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


    //using System.Random;

    public class idk : MonoBehaviour
    {
    public float john = 0f;
    public float epic_gaming = 0f; //time variable
    public int gaming;

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

    // Update is called once per frame
    void Update()
    {
        epic_gaming += 1;
        if (epic_gaming == 120)
        {
            gaming = System.Random(1,10);
            Debug.Log(gaming);
            epic_gaming = 0;
        }
    }
}

缩进在上面的代码中可能看起来很奇怪,所以它适合,但我向你保证它很好。提前致谢。

这与下面发布的另一个问题不同,因为该问题只是关于 C#(我什至在问我之前通读了它),而我的问题源于 Unity 的错误/与这些方法的不兼容。

标签: c#unity3d

解决方案


gaming = Random.Range(1, 10)

如果将 Random.Range 与整数一起使用,它会返回一个 int。

文档:Unity Random.Range()

还将其添加到标题中:using static UnityEngine.Random;

这应该可以解决这个问题:您需要指定 System.Random() 或 UnityEngine.Random()

或像这样使用完整的命名空间:

gaming = UnityEngine.Random.Range(1,10);

推荐阅读