x


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.

more ▼

asked Apr 03, 2012 at 09:31 AM

DarkKobra2020 gravatar image

DarkKobra2020
48 18 12 14

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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);
}
more ▼

answered Apr 03, 2012 at 09:37 AM

Kryptos gravatar image

Kryptos
8.3k 1 9 47

Thank you so much maybe now I can continue my RPG :)

Apr 03, 2012 at 10:31 AM DarkKobra2020

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. Move it to the line after without a variable declaration. Don't use this function in the constructor or field initializers, instead 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.

Apr 03, 2012 at 10:35 AM DarkKobra2020
(comments are locked)
10|3000 characters needed characters left

hp = GetComponent("Health") as Health; //do this at initialization

void OnGUI() {

GUI.Label(Rect(10,10,100,20), "Health:" + hp.curHealth + "/" + hp.maxHealth);

}

more ▼

answered Apr 03, 2012 at 09:38 AM

TheLedworks gravatar image

TheLedworks
37 12 9 10

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4779
x537
x65
x40
x21

asked: Apr 03, 2012 at 09:31 AM

Seen: 2087 times

Last Updated: Apr 03, 2012 at 10:35 AM