Code Ambiguity in Unity

Edit:

Revisiting this post a few years later, as a “seasoned Unity/C# programmer” (see below), and it seems it doesn’t really matter anymore. After a while, stock components/types and custom scripts all meld together as part of the flow of coding in C# with Unity.

Here’s the original post for context:

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:

[RequireComponent(typeof(CharacterMotor))]

// 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:

[RequireComponent(typeof(CharacterMotorScript))]

// snip

motor = gameObject.GetComponent<CharacterMotorScript>();

if(!motor){
  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.