i am writing a game in unity and i want to create one random integer number... i am using the following:
public Random ran = new Random();
public int power = ran.Next(0, 10);
but when i want to run the program it gives me the following error:
Type 'UnityEngine.Random' does not contain a definition for 'Next' and no extension method 'Next' of type `UnityEngine.Random' could be found (are you missing a using directive or an assembly reference?)
Does anyone help me on what is going wrong ???
UnityEngine. Random is a static class, and so its state is globally shared. Getting random numbers is easy, because there is no need to new an instance and manage its storage.
To get a random integer value, pass whole numbers into the Random Range function. To generate a random float, simply pass float values into the function instead. Using float variables, or direct values marked as floats (e.g. 100f) will return a random float number.
You should use the System.Random
class, since this class has a method called Next
. For further documentation on this please have a look here. I suppose that this is your error, since from the error message you get, it's clear that the UnityEngine.Random
class is used and not the System.Random
. In terms of code, I would try this:
public System.Random ran = new System.Random();
public int power = ran.Next(0, 10);
Update
Using the System.Random
we will solve the issue of the naming collision but another problem would be arise. Typing the above two lines inside the body of a class, like below:
public class Program
{
public System.Random ran = new System.Random();
public int power = ran.Next(0, 10);
}
you will notice that the compiler warns you that something wrong is going on and if you try to build your project, you will get the following message:
A field initializer cannot reference the non-static field, method, or property
In order to fix this, there are two options:
a) Make ran
to be static:
public class Program
{
public static System.Random ran = new System.Random();
public int power = ran.Next(0, 10);
}
b) Move the initialization of power
inside the constructor:
public class Program
{
public System.Random ran = new System.Random();
public int power;
public Program()
{
power = ran.Next(0, 10);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With