c# - Random.Range(float, float) 无法通过实例引用访问;用类型名称来限定它

标签 c# unity-game-engine

每当我尝试在两个参数之间生成随机数时,都会出现错误:

Random.Range(float, float) 无法通过实例引用访问;使用类型名称来限定它

我是 Unity 新手,因此我们将不胜感激。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
    public GameObject enemy;
    float randx;
    float randy;
    Vector2 whereToSpawn;
    public float spawnRate = 2f;
    float nextSpawn = 0f;
    Random random = new Random();
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if(Time.time > nextSpawn)
        {
            nextSpawn = Time.time + spawnRate;
            randx = random.Range(-1.408f, 1.232f);
            randy = random.Range(0.776f, 1.232f);
            whereToSpawn = new Vector2 (randx, randy);
            Instantiate(enemy, whereToSpawn, Quaternion.identity);
        }
    }
}

最佳答案

Range 不是实例方法,必须通过其类型访问它。替换这个:

randx = random.Range(-1.408f, 1.232f);
randy = random.Range(0.776f, 1.232f);

这样:

randx = Random.Range(-1.408f, 1.232f);
randy = Random.Range(0.776f, 1.232f);

关于c# - Random.Range(float, float) 无法通过实例引用访问;用类型名称来限定它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62283442/

相关文章:

c# - 在 EF 4.1 中加载所有导航属性及其子属性的最佳方法是什么

c# - 如何通过接口(interface)访问GameObject

javascript - 将 Javascript 转换为 C# 问题

unity-game-engine - 在 Play 上使用设备摄像头而不是网络摄像头

c# - 将数据从 Excel 文件传输到 MySQL 表

c# - C 和 C# 互操作的问题

c# - 如何在table1的指定列之后将table2中的列连接到table1?

c# - 即使集合没有改变,MVVM 从 ViewModel 刷新 Datagrid

android - Android 和 Vuforia 的相机方向错误

user-interface - 如何在Unity顶部显示ui元素