Unity 3 and JS - it's more picky

Here’s the summary: make sure you type all your vars, or you’ll get unexpected results.

Think Pong on the iPhone, with a finger to slide the paddle back and forth. Worked great. Then suddenly, touching the paddle caused it to slide to the right and off the screen. At first I thought that somehow force was being added in the loop, but nothing had changed. I’d added some new sprites with Sprite Manager 2, and thought I’d screwed that up somehow. Nope. Lots of head scratching, until I found that this code, which worked just fine before, in Unity iPhone 1.7:

var previousX : float = 0;

var mx = Input.mousePosition.x;

			if (previousX == 0) {
				previousX = mx;
				}
			else{
				var deltaM = mx - previousX;				
				snip				
				}

was now (under Unity 3) returning deltaM of 0.5, even if the mx input point did not change.

This fixed it:

var previousX : float = 0;
var mx : float;

  mx = Input.mousePosition.x;

			if (previousX == 0) {
				previousX = mx;
				}
			else{
				var deltaM = mx - previousX;				
				snip				
				}

Yes: I know that JS is famously flakey about that kind of thing, especially with iPhone, but I’m posting this because it’s not obvious, and it might give others an idea about where to look if U3 seems to be behaving weirdly with previously good code.

And besides, (as a newb) it’s my first non- question post-back: I finally get to contribute! :slight_smile:

That’s the exact same thing as

var mx = Input.mousePosition.x;

Declaring it the first way doesn’t accomplish anything extra. Doing “var mx = Input.mousePosition.x;” is typing the variable. That’s what type inferencing does.

It’s really not. There are specific rules about how typing and type inference works, which aren’t flakey at all. C# also has type inferencing in Unity 3 and it works the same way. Try this:

var a : float;
a = Input.mousePosition.x;
var b = Input.mousePosition.x;
print ("a is type " + typeof(a) + " and b is type " + typeof(b));

–Eric

I agree with the title U3 being more picky. Allthough i found only one part causing trouble in a recently upgraded project. There i had a c script, declaring some arraylist. Those were filled with strings, which are being read out by a script and then processed. Something like Debug.Log(classname.publicArrayList[0] + " somestring "). In unity 1.7 this worked. In Version 3 it does Not. Now, you have to change arraylist to String[ ] to get that to run.

Actually JS in Unity3 is in fact more picky if you use #pragma strict, since that’s more strict now. You can add #pragma downcast and #pragma implicit to get the old “semi-strict” behavior back. However none of that has any effect on type inference, which works the same as before.

–Eric