[C#]Accessing a variable in an instantiated gameobject

I have the “HQ” script, and some instantiated prefabs (tiles) that all have the script “tile” attached to it. Now I want to alter the variable “test” in one specific object.

HQ script

...
//variable target holds one of the instantiated prefabs
tile targetScript = target.GetComponent<tile>() as tile;

targetScript.test = 1;

...

tile script

...
public static int test;
...

The error: “Static member `tile.test’ cannot be accessed with an instance reference, qualify it with a type name instead”.

It’s drving me mad, I already found some topics on using GetComponent, tried different ways to get rid of the error, but no success. Is there no easy way to just tell Unity: “I want to alter variable X in script Y of gameobject Z”? Maybe somebody could give me a hint on how to solve that problem.

Thanks in advance,

Thomas

You can’t access static properties of a type through instances of that type. If you want to assign properties to a specific instance (as in this case, a component of an instantiated object), you should not declare it static. Just remove the static keyword from the property declaration in your tile class.

public class tile
{
    public int test;
}

Also, when you use generic GetComponent calls (recommended), like you are, you do not need to cast the return type. Thus it’s enough to do:

tile targetScript = target.GetComponent<tile>();

The return type is implicit.

Regards
/Klum

Thanks a lot, this really helps not only to solve my problem but also to improve my bad programming skills :).