- Home /
Accessing variable in another script won't work
So i am trying to acces a variable in another script but it won't work.
This is the variable i am trying to access
public var Energy : int = 5;
And this is the code in the other script that i am trying to access it with.
var Energy : GameObject;
function startGame () {
Energy = GameObject.Find("Scriptforenergy").GetComponent(Energy);
}
function OnGUI() {
if (GUI.Button(Rect(100,100,100,50),"Play")){
Application.LoadLevel("leveltimetestscene");
Debug.Log("Playing");
}
}
Energy is the variable and "Scriptforenergy" is the script i am trying to access the variable in.
Can anyone tell me what is wrong?
Answer by fafase · Mar 21, 2014 at 08:32 PM
You have a variable that is name like a class, you cannot do that. Second your Energy, which should be energy with lower e to differentiate it from the class, is declared as GameObject.
var energy : Scriptforenergy;
function Start () {
energy = GameObject.Find("ObjectName").GetComponent(Scriptforenergy);
}
Finally, you are using startGame method, are you calling it somewhere or did you mean Start which is automatically called by Unity?
Thank you for your respond.
I have edited the code so it looks like this now
var energy : Energy;
function Start () {
energy = GameObject.Find("Scriptforenergy").GetComponent(Energy);
}
And the variable is still the same.
But now it makes the error. The name 'Energy' does not denote a valid type ('not found'). But all the variables i have made are similar so i can't see what's wrong.
What is the name of the script in which energy is stored? That is the type and that is the type you need to use. I assume Energy was the type because you are using in GetComponent. But it seems it is something else. From your description it seems to be Scriptforenergy but then what is the name of the object? I edited the answer.