Four Techniques for Faster Unity 3D Development
By: Yvens Serpa
Tags: Gaming, Programming, Game Development, Game Design, Unity

Four Techniques for Faster Unity 3D Development

Do more with less code and greater flexibility

Unity3D has been my favorite tool for game development for quite some time. I have been using it for over 8 years now, be it for professional products, personal endeavors, and as a programming and game designer teacher. Moreover, I have been using Unity for almost all Game Jams I have been to, and it has helped me quickly build up the cornerstones of my jam-games in just a few hours.

As you might know, a Game Jam is a game development contest in which participants try to make a game from scratch over a short period of time. Game Jams usually range from 24 to 72 hours, but others spam over a more extended period, such as the GitHub Game Off that spans over the entire month of November.

After various Game Jams experiences, which even included one with my group's self-made engine in C++(only available in Brazilian Portuguese, unfortunately), I have developed a shortlist of fast prototyping rules that quickly turned into my tenant for software development: build more with less code.

The main idea of using less code (or to put it another way: to keep a smaller code base) is twofold:

The smaller the code, the fewer the opportunities for bugs to sneak in; Every code change requires updates and tests, which takes time.

For Unity, specifically, there is a third reason: every change in the code will trigger Unity into refreshing, which repeatedly takes a reasonable amount of time.

In this article, I go over a few methods to easily follow this tenant using Unity 3D, speeding up your prototyping methods and overall progress.

Disclaimer: I am not endorsed by Unity 3D Technologies (yet).

1. Serialize Classes and Structs

Serialization is the process of automatically transforming data structures or object states into another format. In Unity's case, this process facilitates the storage and reconstruction of data.

You can mark a Class or Struct as serializable by marking it [Serializable] on top of its name. As seen in the example below from Unity's documentation:

[Serializable]

public struct PlayerStats

{

public int movementSpeed;

public int hitPoints;

public bool hasHealthPotion;

}

The main advantage of using this approach is that it allows for direct access to these properties in the Inspector, especially when using Lists and Arrays.

List of Player Stats in Unity's Inspector. Source: Yvens Serpa.

Your project will likely hold repeated structures, such as Quests, Items, and even Dialogue. In this case, you can make each one of them a serialized Class or Struct and easily change their list of values in the Inspector.

This method also works for enums, great for type safety, and more complex structures, such as Sprites. Both cases are illustrated in the image and code below:

List of Player Stats with Sprites and Enums in Unity’s Inspector. Source: Yvens Serpa.

public enum PlayerType

{

ARCHER, KNIGHT

}



[Serializable]

public struct PlayerStats

{

public int movementSpeed;

public int hitPoints;

public bool hasHealthPotion;

public Sprite face;

public PlayerType type;

}

As an extra, using enums in the serialized structure makes the Inspector display the enum cases in a nice and helpful Combobox. No more concerns about memorizing strings.

2. Use Require Component Whenever Possible

It is ubiquitous to have Scripts with component dependencies. For example, a player controller Script will likely depend on the player's rigidbody and colliders. The safest option to ensure that all dependencies will belong to the game object during the Script execution is to mark it with the Require Component attribute.

The Require Component attribute has three main functionalities:

It forces that the Game Object has the required components. It blocks the required components from being removed. It automatically adds the required components to the Game Object when the Script is attached to it.

An example code of the Require Component usage is displayed below:

[RequireComponent(typeof(Rigidbody))]

public class PlayerScript : MonoBehaviour

{

Rigidbody rigidbody;



void Awake()

{

rigidbody = GetComponent<Rigidbody>();

}

}

These functionalities highly improve the code safety and reduce the chances of unexpected null pointer exceptions by trying to access components that are either invalid or non-existent. You can also either attach them directly on the Editor Window or use the Awake (or Start) methods to get them (as seen in the example code above).

From a prototyping perspective, this approach also makes it faster to set up objects. Furthermore, Classes and Structs can have multiple Require Component attributes at once. Given a Script that does so, just adding it to a game object will attach all of them at once.

Moreover, given that these components will never be invalid under regular circumstances, the Script does not need to check for null. Therefore, less code is written.

3. Use UI Buttons for Multiple Events

This is probably the easiest and more efficient technique of this list: use the same Unity UI Button for multiple events at once. I see many new Unity developers using buttons to either perform a single task or, worse, call a specific method in a Script that handles the button logic.

Whereas having a single task is not necessarily a problem, nor have a specific method for the button logic, both tend to highly depend on changes in the codebase, and changes are very likely to happen.

A better approach is to list all of the effects of a button directly on its OnClick list of events. It can hold up for as many events as necessary, and they are easier to access and change.

You can use this approach, for example, to make a single Button's onClick to display a Unity Panel, play a sound, and trigger an animation. For these particular tasks, no additional code is needed: the Panel can appear ( setActive(true) ); a sound can be played ( play() ); and, the Animator can be triggered ( setTrigger() ). All these method calls are exemplified below.

OnClick list of events example. [Source: Yvens Serpa]

A fairly common usage of this approach is to program a menu's navigation. Each menu will activate the next one and deactivate itself. When returning or closing menus, each one will again deactivate itself and activate the former. The best part of it is that not one line of code is necessary. Again: less code, fewer bugs, more progress.

4. Abuse Unity Events

Unity has a special class named UnityEvent that behaves similarly to using the OnClick method of Unity UI Buttons. An exposed UnityEvent variable grants the Script with the same interface as the OnClick method:

One exposed UnityEvent variable named EventsToBeCalled. Source: Yvens Serpa.

The variable's usage is essentially the same, except that the UnityEvent needs to be invoked via Script to execute its event list. The code excerpt below shows how to add one UnityEvent variable to a Script and how a simple Invoke function is written:

using UnityEngine;

using UnityEngine.Events; public class CallEventsScript : MonoBehaviour

{

public UnityEvent eventsToBeCalled; public void CallEvents()

{

eventsToBeCalled.Invoke();

}

}

The CallEvents method invokes the event list for the UnityEvent variable. Since it is a public method, other Scripts can be accessed, including Timeline's Signals and Animation's Events. For these two cases, no code has to be written to access the method. It is just as simple as dragging and dropping.