-3

Only thing i want is to pick a random X position and random Y position

Random x = new Random(255);
Random y = new Random(255);
int xp = x.Next(0, 255);
int yp = y.Next(0,255);

compile time Error:

Error: CS0236 A field initializer cannot reference the non-static field, method, or property 'Protivnik.x'

Error: CS0236 A field initializer cannot reference the non-static field, method, or property 'Protivnik.y'

Can anyone explain me why is this happening?

Community
  • 1
  • 1
Ivan
  • 69
  • 1
  • 1
  • 5
  • 4
    off-topic hint: you don't need 2 instances of Random class – Selvin Nov 14 '19 at 11:41
  • if you use static method you will have to declare all member variable also static. – Naveen Nov 14 '19 at 11:42
  • 1
    Possible duplicate of [A field initializer cannot reference the nonstatic field, method, or property](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – Selvin Nov 14 '19 at 12:52

1 Answers1

4

You can use that:

static class Program
{

  static Random random = new Random(255);

  static void Main(string[] args)
  {
    int posX = random.Next(0, 255);
    int posY = random.Next(0, 255);
    ...
  }

}

Beware that Next upper bound is excluded, so here it generates [0..254].