Okay let’s take this from the top.
If you remember in an earlier thread you made (a couple of months ago), I mentioned that functions are declared as variables, in the sense that they always have a type. The folly of Unityscript is the fact that you don’t need to specifically declare the type of a function when you declare it, since Unity understands its type through context. However, you can, and this is what the above posters did. Let’s talk with examples.
Just like you can declare a variable of type int, you can also declare a function of type int. The syntax is the following :
var thisVariable : int = 5;
function ThisFunction ( ) : int {
return 5;
}
In this example, thisVariable is a variable of type integer, and ThisFunction is a function of type integer since it returns an integer value of 5.
Note the " : int " after the function’s argument field. This is how we tell Unity what type of function this one is. Also note that in Unityscript we don’t have to do this. Since this function returns 5, Unity assumes it’s an integer function.
So what does return does? The return keyword breaks the function’s execution and returns a result. If you simply type
return;
you return nothing. Likewise you can return any value type you want, for instance
return transform;
What you do with the returned value is up to you. For example we can type
ThisFunction();
And it will do nothing, since we don’t handle the returned value (5). However, we can do
var result = thisVariable+ ThisFunction();
print(result);
which will print 10, since thisVariable equals 5 and ThisFunction returns 5.
I hope you get the grip of what goes on here. So how do we know what type of function our function is? We can check the return. If our function returns a gameObject value, its type is GameObject. If it returns transform, its Type is Transform. If it has a yield, it’s assumed to be a coroutine and cannot return a value, and as long as you have a yield statement in the function’s code, its type is always IEnumerator. If it doesn’t contain a yield and does not return anything, its type is void.