June 30 2020
Have you ever crafted Unity C# code like this?
void ForceUpdateBackend()
{
StartCoroutine(ForceUpdateBackend_Internal(path: Url));
}
IEnumerator ForceUpdateBackend_Internal(string path)
{
var request = UnityWebRequest.Get(path);
yield return request.SendWebRequest();
Debug.Log(request.downloadHandler.text);
}
Somehow, it feels uncomfortable to have two different functions that do kind of the same thing.
Wait, you haven’t written such code?
Okay, what about this pattern?
void AvoidCollision()
{
var penaltyLeft = CalculateCollisionPenalty(-transform.right);
var penaltyForward = CalculateCollisionPenalty(transform.forward);
var penaltyRight = CalculateCollisionPenalty(transform.right);
// drive towards the safest direction
// ...
}
int CalculateCollisionPenalty(Vector3 direction)
{
var didHit = Physics.Raycast(transform.position, direction, out RaycastHit hit);
if (didHit == false)
return 0;
if (hit.collider.CompareTag("Wall"))
return 10;
if (hit.collider.CompareTag("Car"))
return 5;
return 1;
}
The same thing.
It feels as if these extra functions should only be part of our original function
Is another developer going to call these functions by mistake?
There’s no happy ending if sneaky invocations cause side effects in your game.
Can we do something about that?
Hell yeah!
C# 7.0 brought some candy to us, ambitious game developers
Let’s have a look at something new…
Welcome to Unity, C# 7.0 local functions.
We started with a few (simplified) examples of C# patterns I see often in Unity games.
And another one:
void GenerateProceduralUniverse(int randomSeed)
{
for (var levelId = 0; levelId < 10; levelId++)
{
var level = GenerateProceduralLevel(randomSeed, levelId);
// ...
}
}
Level GenerateProceduralLevel(int randomSeed, int levelId)
{
var newLevel = new Level(randomSeed, levelId);
// ....
return newLevel;
}
void GenerateProceduralUniverse(int randomSeed){for (var levelId = 0; levelId Here’s the thing:
No one cares about these extra supporting methods but you.
And I don’t say that to hurt your feelings (I’ve heard we, programmers, don’t have those).
Actually, it’s not even about protecting them from the curious eye.
It’s about protecting our game from someone causing undesirable side effects by calling these “extra” functions.
These side effects can get you canned. Not cool.
The common line is the same:
We write supporting functions to support our original function…
But, at the same time, we don’t want to expose these extra functions to the outside world.
The solution is pretty simple since C# 7.0…
Let’s declare them as local functions.
The idea is simple: we declare these functions inside the main function.
Let’s revisit the three dummy examples.
Often enough, a user won’t care about how your function is implemented.
All a user wants is to call it without messing with weird invocation styles such starting coroutines and such.
We can upgrade the previous example to use Unity C# local functions:
void ForceUpdateBackend_Local()
{
StartCoroutine(ForceUpdateBackend_Internal_Local(path: Url));
IEnumerator ForceUpdateBackend_Internal_Local(string path)
{
var request = UnityWebRequest.Get(path);
yield return request.SendWebRequest();
Debug.Log(request.downloadHandler.text);
}
}
Now you have protected your inner function from the sneaky hands of evil programmers.
Here, we want to avoid code repetition by extracting code into a secondary function.
Let’s upgrade our complicated procedural universe generator:
void GenerateProceduralUniverse_Local(int randomSeed)
{
for (var levelId = 0; levelId < 10; levelId++)
{
var level = GenerateProceduralLevel_Local(levelId);
// ...
}
Level GenerateProceduralLevel_Local(int levelId)
{
var newLevel = new Level(randomSeed, levelId);
// ....
return newLevel;
}
}
Ding! Another level up
Let’s keep it simple.
Here are the advantages of using local functions:
There are significant differences between using C# lambdas and local functions.
Yes, it’s not only a matter of aesthetic preference (that also).
Here are a few:
If you want to read more on local functions (after all, I just served you the appetizer), have a look here*.
* Careful, it’s a Microsoft link. It might set Edge as your default browser.
For the average user, there’s no performance boost by using local functions. If you use lambdas, switching to local functions might help you reduce memory allocations. And that will make your garbage collector happy.
You know what they say…
Happy GC, happy holidays.
What about you?
Have you found any uses for local functions in your game?
~Ruben