Gamasutra is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Gamasutra: The Art & Business of Making Gamesspacer
View All     RSS
July 20, 2019
arrowPress Releases







If you enjoy reading this site, you might also want to check out these UBM Tech sites:


 

Please Encapsulate your Fields

by Lior Tal on 12/22/14 02:36:00 pm   Featured Blogs

The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.

 

Originally posted on http://www.tallior.com

The inspector is Unity's one stop shop for fiddling with game objects' values and is one of the used windows of the Unity editor. The default inspector picks up the properties to display using a set of simple rules (read here).

While the inspector provides an easy way for programmers and designers to easily edit gameplay elements, it does so many times at the cost of code encapsulation. This post shortly discusses this issue and suggests a simple, built-in solution that Unity provides, to better encapsulate your code.

OMG It’s all public !

Consider the following piece of script code:

using UnityEngine;
using System.Collections;
 
public class LaserObstacle : MonoBehaviour
{
    public int DamageAmount;
    public float DamageDuration;
    public int NumberOfBeams;
 
    public GameObject LaserPrefab;
 
    // Implementation details ...
}
 

This results in an inspector that lets you edit all the public fields you exposed in script:

Inspector

 

 

 

 

In smaller projects this may not be such a big issue, but the problem is that this breaks the object’s encapsulation. Once the code base grows and you have thousands of scripts, having all their internal “guts” exposed to all other code can cause serious issues (what implications will changing *this* piece of code have ?)

I don’t blame us all for writing code that’s all public – it’s what we’re all used to seeing for years in many code samples and most of the online resources I’ve seen. I believe the reason for this is that samples usually focus on succinctly getting something done and not dealing with the correct structuring of code.

[SerializeField] to the rescue

So we want to still allow editing scripts through the editor while having the code encapsulated, exposing only what is needed (the code’s public API).

In order to achieve this we can follow this pattern:

  • Set fields on MonoBehaviours to private.
  • Decorate fields that should be exposed in the inspector with the [SerializeField] attribute.
  • (Optional) expose public properties on the script to allow accessing its internal state fields.

The code shown above could be rewritten like so:

using UnityEngine;
using System.Collections;
 
public class LaserObstacle : MonoBehaviour
{
    [SerializeField]
    private int damageAmount;
 
    public int DamageAmount
    {
        get { return damageAmount; }
    }
 
    [SerializeField]
    private float DamageDuration;
    [SerializeField]
    private int NumberOfBeams;
 
    [SerializeField]
    private GameObject LaserPrefab;
 
    // Implementation details ...
}

 

What did we gain ?

 

  1. The inspector for the script looks the same (we can edit it in the same way).
  2. The class does not expose all fields as public.
  3. We can expose the data we want using properties (can also make a property read only by controlling its get/set accessors).

I can not think of  any downside to such code, aside from the extra typing involved. I believe I will adopt this style from now on when creating new scripts.

Lucas from Unity kindly replied to me (on Twitter), saying that aside from typing more, there's no other downsides:

Screen Shot 2014-12-22 at 00.03.13

 

Conclusion

I’ve shown a simple, built-in way, that does not require creating new inspectors or custom editor code, that allows us to have the best of both worlds – working with inspectors and keeping our code encapsulated. I would love to hear any comments or other suggestions whether there are any disadvantages to this code that I clearly missed. Feel free to comment and share you thoughts !

Resources


Related Jobs

DMG Entertainment
DMG Entertainment — Beverly Hills, California, United States
[07.19.19]

Game Engineer
Hi-Rez Studios
Hi-Rez Studios — Alpharetta, Georgia, United States
[07.18.19]

Senior Technical Artist
Hi-Rez Studios
Hi-Rez Studios — Alpharetta, Georgia, United States
[07.18.19]

Unannounced Project - Gameplay Programmer
Build A Rocket Boy Games
Build A Rocket Boy Games — Edinburgh, Scotland, United Kingdom
[07.18.19]

Senior Animation Programmer





Loading Comments

loader image