Error when using getComponent to use a variable

Hi!

I have two script in C#. In the first script i have only the the character’s life and in the second script i try show this variable with the character’s life.

SCRIPT 1:

public class comunicar_script1_c: MonoBehaviour {

	//Con static podemos acceder a la variable desde otro script
	static public int vida = 10;
}

SCRIPT 2:

public class comunicar_script2_c : MonoBehaviour {

	void Start () {
		comunicar_script1_c vidaPersonaje;
		vidaPersonaje = GetComponent("comunicar_script1_c") as comunicar_script1_c;
		vidaPersonaje.vida = vidaPersonaje.vida - 3;
		Debug.Log(vidaa);
	}
}

The console show me this ERROR:

error CS0176: Static member `comunicar_script1_c.vida’ cannot be accessed with an instance reference, qualify it with a type name instead

Anybody knows why?

I’ve also tried with int GetComponent ().vida; and nothing.

Thanks!!

Greetings!

Change:

comunicar_script1_c vidaPersonaje;
vidaPersonaje = GetComponent("comunicar_script1_c") as comunicar_script1_c;
vidaPersonaje.vida = vidaPersonaje.vida - 3;

to just:

comunicar_script1_c.vida -= 3;

This is because static fields (variables) are accessed like this:

ClassName.staticField

and you accessed it like it’s a non static field (meaning: from instance)

Thanks!!, all ok now! :slight_smile: :slight_smile: