Code Ambiguity in Unity

I have stumbled across a lot of ambiguity in code around the web in the context of Unity. Just now, looking at a very stock item – the FPS character controller. I wanted to get a C# version of the CharacterMotor script and FPSInputController script, so that my life is a little easier (all code in C#), and also because I really dislike using js with Unity.

In porting this over, using an example I found, I noticed this section of code:


// snip

motor = GetComponent<CharacterMotor>();

It was not super clear to me (and never really is) when a Component is a built in Component or a custom Script (which is also a type of Component). When I make scripts, I append “Script” to the Component (read: Script) name to be super explicit that I am dealing with a Script. Looking at something like CharacterMotor, and I wasn’t sure if I was dealing with a built in Component type or a custom Script. Turns out I was missing a Script. This wasn’t super difficult to figure out, but it could be a lot easier to figure out. Here’s the new code:


// snip

motor = gameObject.GetComponent<CharacterMotorScript>();

  Debug.LogError("FPSInputControllerScript:: Cannot Find CharacterMotorScript");

I find the latter a lot more friendly for debugging and sharing with other people. If anything goes wrong, it will be abundantly clear why. If the required Script is missing, an explicit error message will call this out. I also typed the additional “gameObject.” prefix so it’s clear where the GetComponent<>() call is going.

I imagine the seasoned expert Unity/C# programmer will scoff at this complete waste of keystrokes. But I know whoever uses this code won’t complain that it’s “too human-readable”. This is something to keep in mind when writing code for other people, selling your Unity assets, or posting examples online. The consumers of your code can always make it “more efficient” by deleting the extra stuff. And if they don’t, there is no real downside.



This entry was posted in Code, Unity. Bookmark the permalink.