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.
I 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:
getting good names on the instances
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.