How To Improve Code in Unity by Reducing Hardcoding

One of the most important things in programming is to make sure that code can handle future changes. While it is important that code does what is has been designed for, it is equally important to make sure that the code is both flexible and extendible. Especially since we live in a world where development requires fast iterations that had to be finished yesterday. One way we can improve code in Unity, is by reducing the amount of hardcoding.

How to improve your code in Unity by Reducing Hardcoding

What is Hardcoding Exactly?

What is hardcoding in programming
Hardcoding is Like Carving

When referring to hardcoding, we usually mean that some values or behaviours are ‘baked’ into the code. Another way of looking at it is that if you were to print out the code, you could actually locate these values and behaviours on paper. As a result, there is no way outside of the code to change these values or behaviours.. So, if you need to edit these you will need to change the code.

Actually, hardcoding is like carving symbols into a rock. The whole rock is heavy and hard to move. It can actually hamper the progress of you project. Also, once hardcoding has been introduced into the rock, it is hard to remove it again.


What Types of Hardcoding Are There?

Usually, we tend to distinguish between two different types. The simplest type of hardcoding is hardcoded values. This type is the easiest to explain since it deals with values that were literally entered into the code by a programmer. An example of this could be a string value that contains a file name. Next, the more complex type of hardcoding is hardcoded behaviours where a series of functions are fixed in a particular order. The best way to picture this is through an in-game cutscene that is completely created in code. In this cutscene, the camera movement, the dialog presented on screen and the sound effects are all baked into the code.


Why is Hardcoding in Programming Bad?

So, why is hardcoding bad? Simply put, it causes your project to become too rigid and resistant to change. Next to that, it prevents game development from being democratized. As mentioned before, if you need to change something, you will have to edit the code. However, editing the code is not always an option since other team members might not know how to code.. In addition, hardcoding is also a problem if you’re a solo developer. Nobody benefits from a project with a rigid codebase. Sadly, because of hardcoding, you are stuck changing your code while you should be developing your game.

Why is hardcoding in programming considered bad

Where Does Hardcoding Come From?

Most often, hardcoding comes from inexperience or because the code just was not a priority at the time. Rather than making the code maintainable, an emphasis was put on making something ‘work’ quickly. From this, it’s easy to see that hardcoding is something that occurs during the prototyping or testing stages.

Another reason for hardcoding is failing to consider that you’re working in a team. While you are programming, you always have to consider who will be using your code. For example, perhaps a designer will use your code to do some balancing in the game. Also, it could be another programmer that needs to touch your code for a new feature. In any of these cases, your team members will benefit from having code that is free from hardcoded values.


Where Does Hardcoding Occur in Unity?

Now that you know more about hardcoding, we can examine where it often occurs in Unity. When looking at value hardcoding, you will often see it occurring in similar scenarios. If you want to improve your code in unity, we urge you to examine the following scenarios in your code when reducing hardcoding:

  • Hardcoding variables like health, ammo, lives or speed in MonoBehaviour Scripts.
  • Not exposing class variables to the Unity Inspector
  • Outputting messages using Debug.Log()
  • Finding an GameObject or Transform by name
  • Comparing GameObject Tags and Layers
  • Loading a Scene by name or Index
  • Finding a Transform Child by name or index
  • Modifying or Creating UI Texts without Localization
  • Giving Objects a certain fixed position, rotation or scale
  • Changing a Material property by name
Situations in Unity where hardcoding is often found.

While it is easy to point at areas where value hardcoding occurs, it is much harder to point at specific situations where behaviour hardcoding occurs. However, there is one sign that usually indicates whether or not a behaviour is too hardcoded. Usually, if a system is not Data Driven enough it can be considered hardcoded. For example, if it is impossible for an AI behaviour to be tweaked through an Editor, chances are big it is too hardcoded.


How To Prevent Hardcoding?

Of course, hardcoding cannot always be prevented. Yet, simply being aware of it can already make a huge difference. In order to make sure the project remains flexible, you must always try to think ahead. You can reduce hardcoding by thinking about how the code could change in the future. What wishes might there be in the future that will impact the code? What values might be needed for that? When in doubt, you should always try defining constants that can be changed later.

As a guide, you can try to prevent hardcoding using the following set of rules:

  • Try to make your project Data Driven as much as possible
  • Expose as much variables to the Unity inspector as you can
  • Use Localization by default for all UI elements.
  • If you need a hardcoded value, place it inside a function so that can be reused in the codebase.
  • Use Constants if all else fails.

How To Track Hardcoding In a Project?

Unfortunately, while elements such as strings and integers are relatively easy to track automatically, other more complex data types are not. Usually, the best way to monitor hardcoding in a project is through manual code reviews. Whenever a new feature is complete, try reviewing it and specifically check for hardcoding and check if the code is extendible enough.

Another way to check is introducing a workflow that captures and documents hardcoded values. Below you can find an Utility class that does just that. Every time you need a hardcoded value, you can wrap it in the Hardcode.Value method along with an optional description. Whenever the value is accessed, it will output a message to the Console to notify a developer that a hardcoded value is present.

HardcodingUtility.cs
  1. using UnityEngine;
  2.  
  3. public static class Hardcode
  4. {
  5. public static HardcodedType Value<HardcodedType>(HardcodedType value)
  6. {
  7. return Hardcode.Value<HardcodedType>(value, string.Empty);
  8. }
  9.  
  10. public static HardcodedType Value<HardcodedType>(HardcodedType value, string description)
  11. {
  12. Debug.LogWarningFormat("Warning, use of hardcoded value of type {0} with value {1}: '{2}'", typeof(HardcodedType), value, description);
  13. return value;
  14. }
  15.  
  16. public static HardcodedType SafeValue<HardcodedType>(HardcodedType value)
  17. {
  18. return value;
  19. }
  20. }

In the example below, we are marking a hardcoded value and are documenting it at the same time. Everyone can see that this is a hardcoded value and why it was put in place.

PlayerHealthModifier.cs
  1. public void AppyDamage()
  2. {
  3. int playerDamage = Hardcode.Value(2, "Waiting for Mark to finalize the new damage multiplier system");
  4. player.ChangeHealth(-playerDamage);
  5. }

Common Examples of Hardcoding in Unity

Finally, below you can find some examples that will illustrate how you can improve your code in Unity by reducing hardcoding. While the list is far from complete, we do belief it helps to further illustrate what hardcoding in Unity looks like.

Finding GameObjects by Name

In this example m_SerializedPlayerObjectName is a variable exposed to the Unity Editor.

// Hardcoded String - Bad
GameObject.Find("Player")
 
// Constant - Good
GameObject.Find(Constants.PlayerObjectName);
 
// Value stored inside variable - Good
GameObject.Find(m_SerializedPlayerObjectName);

Finding Child Transform by Index

In this example, PlayerWeaponTypes is an Enum that has values for the different kind of weapon types available in the project.

// Hardcoded Index - Bad
var child = transform.GetChild(2);
 
// Constant - Good
var child = transform.GetChild(PlayerWeaponTypes.Shotgun);
 
// Function to access child - Good
var child = GetWeaponObject(PlayerWeaponTypes.Shotgun);

Logging Error Messages to the Unity Console

// Hardcoded String - Bad
Debug.LogError("The requested save file could not be found!");
 
// Error Message as Constant - Good
Debug.LogError(ErrorMessages.SaveFileNotFound);

Summary

What we hope you have learned from this article:

  • When referring to hardcoding, we usually mean that some values or behaviours are ‘baked’ into the code.
  • The simplest type of hardcoding is hardcoded values.
  • A complex type of hardcoding is hardcoded behaviours.
  • Hardcoding causes your project to become too rigid and resistant to change.
  • Editing the code is not always an option since other team members might not know how to code.
  • Because of hardcoding, you are stuck changing your code while you should be developing your game.
  • Hardcoding comes from inexperience or because the code just was not a priority at the time
  • Hardcoding happens when failing to consider that you’re working in a team.
  • You can reduce hardcoding by thinking about how the code could change in the future.
  • The best way to monitor hardcoding in a project is through manual code reviews.
  • Another way to check for hardcoding is introducing a workflow that captures and documents hardcoded values.
Summary of what hardcoding is and how you can improve your code in Unity by reducing it.

Conclusion

To conclude, we have learned what hardcoding is and that it leads to a project that is resistant to change. When working in a team or alone, it is always good to keep an eye on hardcoding and to prevent it. To do this, a good practice is to think how the code could change in the future. Also, it is important to review any code for potential hardcoding that threatens the flexibility of the project. As you gain experience, you will find that it’s easier to spot potential hardcoded values and behaviours. In the end, we hope you are now able to see that you can improve your code in Unity by reducing hardcoding.