0

In my unity project I have a grid which I coded the columns and rows like this:

public int rows = 10;
public int columns = 10;

But then when i try to set the value of another variable like this:

Total = columns * rows;

It gives me the following errors:

A field initializer cannot reference the non-static field, method, or property 'Enemy.rows'
A field initializer cannot reference the non-static field, method, or property 'Enemy.columns'

However it does work if I use => instead of = and I wanted to know why. The only thing I can think of is because the values of columns and rows can change. I know => is a getter but I don't understand much about it as I am new to unity/c#.

1 Answers1

0

As you may read in the c# Specification, "A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name".

class A
{
    int x = 1;
    int y = x + 1;        // Error, reference to instance member of this
}

The typical way to encounter this error is on the attemp to set an array size at the instance field variable initializers of a class, which throws the Compiler Error CS0236 for the very same reason.

public class MyClass : MonoBehaviour{

    int size = 6;
    float[] f = new float[size]; //not allowed

    // Start is called before the first frame update
    void Start()
    {
      //some code
    }
}
rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47
  • How about the second part of the OP question? With the =>, I'm curious... – Gonen I Aug 28 '21 at 17:55
  • I think [this](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#properties) explains it: "However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. Properties thus provide a mechanism for associating actions with the reading and writing of an object's attributes; furthermore, they permit such attributes to be computed." – rustyBucketBay Aug 28 '21 at 18:07