- Home /
Can I declare a variable inside a function which has instance scope?
I have a prefab containing a script that has several member arrays (builtin arrays). Another script creates each instance of this prefab and sizes the arrays differently.
At present, I am declaring the variables at the top of the script, then calling the initialization function from the other script, which gives it the size of its array:
private var things; private var thingSize : int[];
function MakeThings(numberPassedFromOtherScript) { things = numberPassedFromOtherScript; thingSize = new int[things]; for (a=0;a<things;a++) { thingSize[a] = Random.value*10; } }
Is there a way to instead declare the variables inside that MakeThings() function, sizing them at the same time, and still have access to the variables and arrays after MakeThings() ends? Something like this... (I know I'm using global incorrectly here, this is just for illustration.)
function MakeThings(numberPassedFromOtherScript) { global var things = numberPassedFromOtherScript;
global var thingSize = new int[things]; for (a=0;a < things; a++) { thingSize[a] = Random.value*10; } }
What would be the advantage of doing it that way? As far as I can see, it would only complicate things and make the code harder to maintain ... which is probably why this isn't possible (at least not in any language I would program in ;-) ).
Answer by jashan · Aug 05, 2010 at 11:30 AM
No, obviously, scope is defined by the declaration - so if you declare a variable inside a method, it has method scope. What would be the use of having member variables declared in a method anyways, except for making things complicated and hard to understand? ;-)
Thanks! I kinda thought so. Sometimes one has to ask stupid questions in order to learn ;-)
Jashan - unfortunately, you actually can declare a global scope variable inside a function inside normal javascript (Which makes things less obvious). I expect that's where some of the confusion comes from
Hi $$anonymous$$ike, ah ... yeah ... "regular JavaScript". I wasn't aware that this is possible but I can totally understand how this is confusing. Actually, that's one of the reasons why I usually write UnityScript - to make the distinction because it's really quite confusing to have a language named "JavaScript" which is so different from browser JavaScript. And, yeah, I can imagine that browser JavaScript supports such oddities ;-)