<aside> ✨ Foreword: I'm starting this new series (hopefully) of tips on Unity project architecture. I'm trying to see if that kind of stuff can be helpful for newcomers and intermediate Unity users who are struggling with software architecture questions. I posted more ideas for future topics here. Please let me know what you think! — Lazlo (@lazlobon)
</aside>
In this tip you'll learn how to create global constants in your Unity project that you can easily:
The end result of your code will look like the following when you're accessing global constants:
In this example, we're defining a coroutine that gets launched when the hero opens a chest. We first wait for set a duration in seconds for the animation to play; that duration is a global constant. Then, we instantiate coin prefabs near the chest; the prefab to use is also a global constant.
using UnityEngine;
using System;
using System.Collections;
using static Game.Facade;
namespace Game
{
public class Chest : MonoBehaviour
{
public IEnumerator Open()
{
yield return new WaitForSeconds(config.chestOpeningDuration);
for (var i = 0; i < this.coinAmount; i++)
{
Instantiate(config.coinPrefab, transform.position);
}
}
}
}
Notice a few neat things about the code above:
config
anywhere; it is global!Config.instance
Game.Facade
hack takes care of that for us!coinPrefab
, not only primitives like strings and floatsAnd most importantly, the values of config are set from the inspector, not from code. This means it's fast and easy to iterate on your game, and your designer(s) can edit values in without having to touch the code at all. The end result in the inspector will look something like this: