- Home /
Accessing a variable within a function.... GetComponent()
I know how to get a variable that is public but how would I get one inside a function (Update function)?
Is it somewhat like this?
var script = GetComponent(ScriptName).Update();
script.variable = blah;
Answer by Eric5h5 · Jul 28, 2010 at 05:54 AM
Variables declared inside a function are local to that function and can't be accessed outside by any means. Any variables you need to access from other scripts must be public.
then how would I do something where I want a variable to be half of another variable and I want to update it every frame? (and still be able to reach it in another script)
@$$anonymous$$ikezNesh, just declare any variables used in the function that you want to access outside as public variables.
like public var blah? then I get an error: epecting } found 'public'.
@$$anonymous$$ikezNesh, no. Like I said, you cannot make variables declared inside functions public by any means. Just declare any variables used in the function that you want to access outside as public variables. Do not declare them inside the function. See Smorpheus's answer.
@$$anonymous$$ikezNesh, just declare the variable outside the function and assign the value inside it.
Answer by Thom Denick · Jul 28, 2010 at 05:56 AM
You need to declare the variable as public before the Update Function. Then you can use this same variable in your Update Function and access it directly via an outside script as you've demonstrated.
Just about any script has this implemented, for example:
var guiCenter : Vector2;
function Update() { guiCenter.x = 5; }
In JS, public is the default attribute of any variable you declare outside of a function.
Your answer
Follow this Question
Related Questions
Can't understand generic getComponent for Js 1 Answer
Help with accessing scoring system variable C# plz. 3 Answers
variable doesn't change 1 Answer
AddComponent with parameter variable 2 Answers