Hi! Im new at monogame and im currently trying to create a random int to use in my damage. However i cant get it to work. The “r” is marked red with the error: “A field initializer cannot refrence the non static field, method, or property ‘Red.r’”
Would be really glad if someone could help me
class Red : Monster
{
Random r = new Random();
public int random = r.Next(0, 5);
int specialattack = 5;
public Red( int hp, int atk) //konstruktor för Red
{
healthpoints = hp;
attack = atk;
}
public void SpecRed() //ökar reds attack med 5
{
attack = attack + specialattack + random;
}
“random” here is a field, which can’t be initialized by calling code like that. You wouldn’t want to do it like this anyway, it will call r.Next once to set the value of random… so that number would never change
You can change “random” to be a property, which will do what you are wanting. The latest c# added some sugar that will fix this nice and tidy: public int random => r.Next(0, 5);
The right-arrow under the hood creates a “get” property which will call that bit of code every time you hit “random”
Hope this helps, cheers!
use dmanning23’s solution, it’s better. I just looked at the code to fix the issue but the use you want to give to that random variable is what dmanning23 is saying.