Unity JavaScript/UnityScript method lookup Bug or design flaw


Just wasted 2 hours chasing some code that wasn’t doing what I told it to (bad code!) only to find that I’d made a mistake (of course) and the compiler hadn’t told me about it (bad compiler!).

I don’t know if the root cause is that JavaScript/UnityScript method lookup rules are completely broken and don’t make any sense compared to any real object oriented language or if this is a bug, but I thought I’d document what is an easy mistake to make and encourage people deciding between JavaScript/UnityScript and C# for their Unity development to choose C# to avoid this kind of garbage.

Here’s the situation:  you are in a script and want to get a child node of the current object.  So you mistakenly type  gameObject.Find("MyMeshName");  and the compiler is fine with this and no errors or warnings are emitted but things aren’t working the way you thought they should…

That’s because there is no Find(…) Instance Method IN GameObject or its superclass Object.  Nice of the compiler to tell you that, eh?  Oh, right, IT DIDN’T!!!  Instead it decided to do the helpful (not!) thing and call the GameObject Find(…) class method.  DOH!  This class method, unfortunately, does a Global Search and returns you the first “MyMeshName” found anywhere in your entire game.  My how completely opposite of what you wanted.  <sigh>

What you meant to type was transform.Find("MyMeshName") and then get the gameObject from the returned transform and you would have gotten what you wanted – the game object associated with the mesh “MyMeshName”.

Or GameObject should have a way to search inside it’s children without having to get the transform and search and then ask the result for it’s game object.  Seems like searching/traversing the game object hierarchy is about as basic a thing as one would want to do in a game engine, but apparently I’m confused or something…


Just did a test and the C# compiler correctly tells me that there is no Instance method Find(<string>):


Assets/TestMethodLookup.cs(9,44): error CS0176: Static member `UnityEngine.GameObject.Find(string)’ cannot be accessed with an instance reference, qualify it with a type name instead


So this is seems to be either a JavaScript “feature” that is one more nail in the JavaScript coffin or a bug in the JavaScript/UnityScript in Unity 3d.

(Reported to Unity as Case ID: 492421)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: