x


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?

more ▼

asked Jan 15 '11 at 09:06 PM

schwertfisch gravatar image

schwertfisch
370 53 57 68

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

1 answer: sort voted first

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

answered Jan 15 '11 at 09:12 PM

Mike 3 gravatar image

Mike 3
30.7k 10 67 255

Thanks a lot Mike, 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. OK, maybe my question was a very silly, but it seemed really confusing just before you answered...

Jan 15 '11 at 09:20 PM schwertfisch

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

Jan 15 '11 at 09:25 PM Mike 3

Got it- thanks again Mike ;-)

Jan 16 '11 at 09:52 AM schwertfisch
(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:

x850
x498
x111
x46
x22

asked: Jan 15 '11 at 09:06 PM

Seen: 1605 times

Last Updated: Jan 15 '11 at 09:11 PM