- Home /
Ternary operator fails, but verbose comparison doesnt?
Trying to write neat & compact code Im confused as to why in UnityScript this fails with error BCE0022: Cannot convert 'Object' to UnityEngine.Vector2...
var useTouch : boolean = true;
position = useTouch ? Input.touches[0].position : Input.mousePosition;
...yet the following is fine. Are they not essentially the same?
var useTouch : boolean = true;
if( useTouch )
position = Input.touches[index].position;
else
position = Input.mousePosition;
I just tried different versions but almost every one worked and i never get this error. Are you sure you get that error on the ternary operator line? Is position defined above or is it implicitly created here? Another thing: You just access touched[0] but if there is no touch at all you will get an index out of bounds error because the touched array will be empty. Without the code above and/or below i can't see anything else wrong.
Positive I get it on this line. I comment it out, everything works, uncomment, fail. position is defined elsewhere, and used elsewhere fine. Im also checking that there are touches (note, Im not getting an out of bounds error, but the Object to Vector2 casting error)
Im also using #pragma strict, but it fails without as well.
Answer by loopyllama · Mar 10, 2011 at 10:08 PM
Input.touches[o].position is a vector2 and Input.mousePosition is a vector3. You are using javascript which, for better or worse, allows you to not declare what type position is. in your second working example it is clear that one case position is a vector2 and in another case it is a vector3. In your failing example you are saying if this is true, position is a vector2, and if it false it is a vector3, but it happens at runtime. At compile time which is it? it cannot be both a vector2 and vector3 so it fails. Try explicitly casting the vector2 to a vector3 in your first example and that should work..like Vector3(Input.touches[0].position.x,Input.touches[0].position.y,0.0F)...or maybe even (Vector3)Input.touches[0].position would work, you'd have to try and see.
Perfect. Vector2(Input.mousePosition.x, Input.mousePosition.y) works as well, and its a bit less code. Thanks!
Well, i don't develop for iphone so i usually don't use Input.touches
;). Good to know that the position of a touch is a Vector2. +1
Your answer
Follow this Question
Related Questions
How can I compare directions of objects 2 Answers
Having random operators in an equation? 1 Answer
question mark in "setPixel" documentation example? 1 Answer
Shorthand for checking for multiple if's..... 2 Answers
Overload Operator in UnityScript? 0 Answers