- Home /
In a function, how do I access a variable of another function in the SAME script? (js)
I have a script, with 2 functions. These 2 functions are called at different moments, by another script on another gameObject.
The first function, creates a variable (it's the length of an array that this 1st function creates at runtime using "GameObject.FindGameObjectsWithTag").
I want to use this variable that the 1st function creates in the 2nd function, but when I put it in the 2nd function like this:
while (varName >=1) { ...
I get the error:
"varName" is not a member of 'function ():void'
What should I do then, to use in the 2nd function, the variable that the 1st function creates?
Answer by Mike 3 · Jan 15, 2011 at 09:12 PM
You need to declare the variable outside of the functions. That way, it's in the scope of the class, which lets you use it from both functions
i.e.
var test : int;
function a() { test = 4; }
function b() { Debug.Log(test); }
Thanks a lot $$anonymous$$ike, I thought that since the var's value (which is the length of an array created at runtime, as I said) should be defined through the 1st function, I should also set the var itself in that function. What I did now, was setting the variable at the beginning of the script, without giving it a value. The 1st function does that and I can use it in the 2nd function. O$$anonymous$$, maybe my question was a very silly, but it seemed really confusing just before you answered...
The problem is that a variable declared in a function only exists while that function is running. I have a feeling web javascript handles it differently, but that's another issue entirely
Your answer
![](https://koobas.hobune.stream/wayback/20220613095619im_/https://answers.unity.com/themes/thub/images/avi.jpg)