Random.Range(float, float) cannot be accessed with an instance reference; qualify it with a type name instead

Viewed 218

Whenever I try to generate a random number between the two parameters it gives me the error:

Random.Range(float, float) cannot be accessed with an instance reference; qualify it with a type name instead

I am new to Unity, so any help would be greatly appreciated.

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

Range is not an instance method, it must be accessed via its type. Replace this:

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

with this:

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

Random.Range is a static function, so instead of calling it on an instance of Random, you would have to call it on the type name. So just like you do now, but lose the "new Random()" stuff and just say Random.Range(...).

Most functions on .NET Random are Instance functions. You need a instance to work on them. And the standing advise is to re-use instances as long as possible (creating multiple ones will worsen randomness and can go all the way using the same values).

.NET Random does not have a Range(Float, Float) function. Indeed it does not have a single static Method I could find. So you are either using Mono's Random, a 3rd party random or there are some exenstion methods floating around.

In either case, the compiler did find a Range function that is marked as static. Static functions have to be called on the type itself, not on instances. Similar to how you run Float.TryParse(). Or that static property Time.time (wich I asume is like DateTime.Now).

Related