🤔

CS0120#

An object reference is required for the non-static field, method, or property 'Foo'

Types are usually created as instances. This means that there are individual objects, and a variable can reference one of them.

static is a keyword that restricts something to a single instance, bound to the type name. Static is not to be liberally applied. Generally the correct way to solve this error is to properly reference an instance.

Resolution#

In non-static methods#

Reference the instance you care about, instead of its type. See referencing members in other scripts if you are trying to access content in another script.

Example#

void Update()
{
Transform.position = newPosition;
}

Transform is the name of the class, but which Transform is this referring to? position isn't defined statically, because each individual Transform has a position.

The code must define which instance it is positioning.

In this case Component has a transform property defined which is the Transform they are attached to.

transform.position = newPosition;

In static methods#

Static methods cannot access instance members (not static), only other static members.

warning

Liberally applying the static keyword is not a solution to reference objects.

For example, if you have a static method on a MonoBehaviour, a non-static property like transform is not accessible. Static variables also aren't serializable, so inspector-defined variables can't be referenced directly in static methods.

Continuing to use a static method#

If you want to access an instance member inside a static method, it must be passed as in as a parameter.

Switching to an instance method#

Question whether your method should be declared as static, and consider properly referencing an instance of your class instead. In cases where you have a singular manager class (a score manager for example), you may consider using a singleton.