- Home /
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!
Answer by andrew-lukasik · Aug 21, 2014 at 12:12 PM
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 Andrew, but now the console show me "The referenced script on this Behaviour is missing!" and don't show the varible.
This often happens when you rename/delete project script outside Unity Editor so it don't know how to find this script when it's referenced in prefabs or scene's gameobjects. To fix this find this gameobject and in Inspector re-assign proper scripts again (or delete empty reference when it's not needed anymore)