Random int

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 :smile:

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;
    }

Hi! It’s not a monogame question but a C# question. Error messages can seem a bit cryptic when starting.

Simplified:

"A field initializer ( r.Next (0,5) ) cannot reference the […]. property ‘r’ " ,

or in other words, you can’t use r.Next (0,5) as initializer of a variable inside your class ‘Red’.

in order to fix it, just move the initialization to the constructor:

class Red : Monster
{

Random r = new Random();
public int random;
int specialattack = 5;
public Red( int hp, int atk) //konstruktor för Red
{
    random = r.Next(0, 5);
    healthpoints = hp;
    attack = atk;
}

...

“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 :frowning:

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!

Thx alot! It worked perfectly cheers!! :smile:

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.