Reputation: 55
I just have a basic question. I'm trying to learn how to use functions with unityscript and I learned that when you create a function using something like
function Example(text)
{
print(text);
}
and then call it up using
Example();
you can actually insert a string or a number into the parentheses on the latter piece of code in the parentheses and it will pass through and insert itself into the function you created previously. In this case, it does end up printing whatever I type into the parentheses.
Now, my question is if that works, then why don't functions where I pass in two numbers and ask to have them added work? The code I'm trying to use looks like:
Addition(4, 4);
function Addition(a, b)
{
print(a+b);
}
When I try to execute this, Unity tells me
Operator '+' cannot be used with a left hand side of type 'Object' and a right hand side of type 'Object'.
I was watching this video on Javascript functions and in the video at around 9 minutes, the guy types in exactly that, and gets the script to add it for him. I'm rather new to scripting and I do not have much of an idea of what I could be doing wrong. Thanks in advance for the help.
Upvotes: 5
Views: 821
Reputation: 6132
Actually, in Unity your code would have to look like:
Addition(4, 4);
function Addition(a:int, b:int)
{
print(a+b);
}
You'd have to call what type of argument you expect in the function's parameters. You are completely right by stating that in JavaScript this normally isn't needed. In Unity, it is though.
This is because it is actually called UnityScript
. UnityScript is the name used by people who want to point out that Unity's Javascript is very different from the traditional version of Javascript used in browsers.
I have found a nice list of differences for you between UnityScript
and Javascript
here. When I create a quick bulletlist out of that web page, I can tell you the differences are (perhaps not even all):
var
statement is global.with
statement in UnityScript. Regular Expression Literals
(RegExp
or regex
).this
can refer to one of two things, depending on the context:
I have retagged your question to categorize it in UnityScript as well. StackOverflow has this to say about it:
Unity's JavaScript tries to follow the ECMAScript standard closely, it varies in many ways from other implementations of JavaScript that are based on the same standard. It is perhaps most similar to Microsoft's JScript, especially in that both are .NET languages. However, Unity's version was developed independently and there are a number of differences between the two.
I, too, had to find out the hard way. I messed up the two languages and got to this problem.
Upvotes: 5
Reputation: 490233
Unity JavaScript for some reason is not making those 4
as primitive Number
types, so it can't perform addition.
You could try converting them to primitive by calling their valueOf()
method.
Upvotes: 0