Cannot create an instance of the static class 'Random'

Viewed 5308

Hi Ive switched from regular coding to using Unity and Im getting errors for seemingly simple stuff. Here it is and Thanks in advance.

Error: Assets/Starting Biome.cs(8,18): error CS0712: Cannot create an instance of the static class 'Random'

Error: Assets/Starting Biome.cs(8,7): error CS0723: Cannot declare a variable of static type 'Random'

Error: Assets/Starting Biome.cs(9,23): error CS1061: 'Random' does not contain a definition for 'Next' and no accessible extension method 'Next' accepting a first argument of type 'Random' could be found (are you missing a using directive or an assembly reference?)

Here's my Code:

    using UnityEngine;
    using System.Runtime;

    public class StartingBiome : MonoBehaviour{
    // Start is called before the first frame update
    static void StrBiome(){
      var RndB = new Random();
      int StrB = RndB.Next();
    }
    void Start()
    {

    }
    // Update is called once per frame
    void Update()
    {

    }
    }
2 Answers

There is the static class UnityEngine.Random and there is System.Random.

Since you have the

using UnityEngine;

in your script but not

using System;

for the compiler it is clear that you are referring to UnityEngine.Random.


Now you can either use explicitly

var RndB = new System.Random();
var StrB = RndB.Next();

Or add a

using Random = System.Random;

at the top of your script and then use what you have.

var RndB = new Random();
var StrB = RndB.Next();

The UnityEngine.Random is specifically made for float (Random.value). For int values you have to go via UnityEngine.Random.Range and to get the same behavior as the System.Random.Next (which only returns positive values) you would have to rather do

using UnityEngine;

...

var StrB = Random.Range(0, int.MaxValue);

Now which of these two you chose is a question of preference.

With the System.Random you create an instance, use it once and throw it away .. but that shouldn't really matter in your case.

When using Unity, you should use Unity's own random number generator. You can use it like this:

StartingBiome.cs

using UnityEngine;

public class StartingBiome : MonoBehaviour
{
    // Start is called before the first frame update
    private static void StrBiome()
    {
        var strB = Random.Range(0, int.MaxValue);
    }

    private void Start()
    {
    }

    // Update is called once per frame
    private void Update()
    {
    }
}

This is the equivalent for C#'s "random.Next()". It returns a random number within the Int32 range that is equal or greater than 0. If you want to use a smaller range, replace "0" with the start of the range and "int.MaxValue" with the end of the range (start is inclusive, end is exclusive). You can also use floats. In that case, both the start and the end of the range are inclusive.

Happy coding!

Related