- Home /
Unities Javascript, declaring and using a non-generic function
var num = 0;
var randomize = function(x){
x = 1;
};
randomize(num);
print(num);
okay in real JS this should print to the console "1" but it doesn't it prints 0. why is that? i know that Unityscript and JS are different but this has me confused.
how can I make and utilize a non-generic function? thanks
Answer by IvovdMarel · Jun 12, 2014 at 11:23 PM
You're not changing num, you're just using it in the method.
function should return x.
function randomize (x : int) : int {
return Random.Range(0, x);
}
function test () {
var num : int = 10;
num = randomize(num);
print(num);
}
I'm a C# programmer, I think this should work tho
Answer by rutter · Jun 12, 2014 at 11:22 PM
okay in real JS this should print to the console "1"
num is passed by value, which means that the x inside your randomize function is a copy of num. Changes to the copy won't affect the original.
If you'd like to learn more, search for a decent tutorial on "pass-by-value" versus "pass-by-reference".
To change the value of num, you could pass a value back:
var num = 0;
var randomize = function(x){
return x+1;
};
num = randomize(num);
print(num);
Answer by Kiwasi · Jun 13, 2014 at 12:32 AM
C# can do this by using the ref keyword in your method declaration. I assume JavaScript has some sort of equivalent functionality. However I would recommend using the return methods shown in the previous answers.
int num = 0;
private void randomise (ref int x){
x = 1;
}
void testMethod (){
print(num);
// The console will show 0
randomise(num);
print(num);
// The console will show 1
}
Your answer
Follow this Question
Related Questions
private Vector3 function? 2 Answers
calling c# function from a js file.. 1 Answer
Accessing functions on external JS in the same object 0 Answers
what is the problem of this code ? 2 Answers
[SOLVED] Cycling all the way through weapons properly 1 Answer