- Home /
Calling variables from other scripts
Ok I have followed every single question and I even looked at the manual and this is getting ridiculous. I keep trying to call my variables curHealth and maxHealth for a GUI script from the Health script
var health : Health = GetComponent(Health);
function OnGUI() { GUI.Label(Rect(10,10,100,20), "Health:" + health.curHealth + "/" + health.maxHealth); }
@script RequireComponent (Health)
I either get errors that say that variables can not be called using the GetComponent function but if I do it the way it says in the manual it will just say it needs a reference.
Answer by Kryptos · Apr 03, 2012 at 09:37 AM
You cannot get the component upon the declaration of the variable (it might not be ready at that time). What you need to do is retrieve the component during the Awake phase:
@script RequireComponent (Health)
// declaration
var health : Health;
// retrieve component
function Awake()
{
health = GetComponent(Health);
}
// use it
function OnGUI()
{
GUI.Label(Rect(10,10,100,20), "Health:" + health.curHealth + "/" + health.maxHealth);
}
Thank you so much maybe now I can continue my RPG :)
Ok in normal curcumstances you would be correct but I think there is something wrong with my version of Unity as its now giving an Argument exception.
ArgumentException: You are not allowed to call GetComponent when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration. Don't use this function in the constructor or field initializers, ins$$anonymous$$d move initialization code to the Awake or Start function. HUD..ctor () (at Assets/Scripts/Player/HUD.js:1)
All I did was copy your code to see if it would work.
Answer by TheLedworks · Apr 03, 2012 at 09:38 AM
hp = GetComponent("Health") as Health; //do this at initialization
void OnGUI() {
GUI.Label(Rect(10,10,100,20), "Health:" + hp.curHealth + "/" + hp.maxHealth);
}