- Home /
Why isn't my java code working?
I'm quite new to java so this may sound abit dim. I've been doing some video tutorials for unity this is the code that I have writen:
var box;
box = "small box";
print(box);
var boxNumber;
boxNumber = 23;
print(boxNumber);
var boxTotal;
boxTotal = boxNumber + box;
print(boxTotal);
It is supposed to display the words small box + the box number but is keeps giving me this error: Assets/scripting basics.js(31,30): BCE0051: Operator '+' cannot be used with a left hand side of type 'Object' and a right hand side of type 'Object'. What does the error meen cause im quite puzzled by it.
Any help would be much appreciated, thankyou very much.
Answer by Bunny83 · Aug 24, 2012 at 03:47 PM
Like Semicolon said you should give your variables a type. Mono / .Net is a compiled and type safe language. When you don't provide a type, it's type will be a dynamic "Object". Dynamically typed variables are slow since the runtime has to check the type when you use the variable. Also, like the problem you have here, since the type is not known at compile time you can't use operators like + on that type since it could be a string, a class, null, or whatever.
Next thing is you try to add a string to a number. That doesn't work unless you convert the string into a number. However your string doesn't contain a numer, so do you want to concat the numer as string with the other string?
var box : String;
box = "small box";
print(box);
var boxNumber : int;
boxNumber = 23;
print(boxNumber);
var boxTotal : String;
boxTotal = boxNumber.ToString() + box;
print(boxTotal); // Should print "23small box"
A final note: Java is a completely different language as JavaScript. Additionally the "JavaScript" variant that is used in Untiy is also quite different from traditional JavaScript. That's why it's actually called UnityScript.
Answer by Semicolon · Aug 24, 2012 at 03:22 PM
That means that it hasn't been instructed on how to add 2 Objects.
Try using "var :String;" instead. So:
var box:String;
Your answer
Follow this Question
Related Questions
SCRIPT NOT WORKING 2 Answers
Animation script error 1 Answer
Console Error 1 Answer
OnMouseEnter Error 1 Answer