Unity3d: Giving runtime prefab instances meaningful names

This is a short note about a minor issue you may meet in Unity3d when you are creating scene objects in code, say from prefabs.

In my case I am creating a soccer field borders on the base of a grid that may resize, so I want to create everything in code.

Unity3d object instance with meaningless nameI am as always giving meaningful names to variables (and you should too) and so it would be nice to get the instance to be named as the variable, without duplications and without – oh horror – writing the instance name as string, breaking code esthetic and refactorings. In the pic on the side you see what you get by default – not cool.

Actually in the rich and hackable C# universe as managed in current Unity3d this is possible: just this way:


Thanks to this post here. I used it this way:


imagegetting good names on the instances Sorriso


Note that this relies on unspecified behaviour and while it does work in Microsoft’s current C# and VB compilers, and in Mono’s C# compiler, there’s no guarantee that this won’t stop working in future versions. See the discussions here:

Getting names of local variables (and parameters) at run-time through lambda expressions

Finding the Variable Name passed to a Function in C#

Update: It seems like this might no longer be an issue from C# 6, which will introduce the nameof operator to address such scenarios.

If you have suggestions on how to automate getting good instance names at runtime (maybe with cleaner / lesser code) let me know!

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, serious games.

Social Share Toolbar


  1. Does this work on iOS? With the AOT compilation and all that might be an issue. Reflection usually is something quite costly as well, perhaps you should only do it in editor when you instantiate a lot of objects.

    • Thanks, good points. On iOS unfortunately I have no experience, maybe someone can help?
      For the cost of reflection, yes it depends, in my case being a once-per-scene instantiation it is not a problem.

  2. This will probably not work on iOS.

    Also, C# 6 does have the nameof operator, too bad that as it seems, we’re not even remotely close to having support for that in Unity (or a new Mono version…)

Speak Your Mind