About a year ago we saw how easy it is to use code generation to go beyond the limits of C# generics. The system we used simply replaced strings in a template file to generate a C# file. Today we’ll go way further and radically increase the power of the code generator by using some simple, off-the-shelf tools.
Posts Tagged code generation
The series continues this week by addressing a pretty important issue. Previously, we were limited to doing all our work in just two C++ functions:
PluginUpdate. This isn’t at all the normal way to work in Unity. It’d be a lot more natural to write our code in
MonoBehaviour classes. So today we’ll come up with some tricks to allow us to write our
MonoBehaviour code in C++ so we are truly scripting in C++.
Last week in the series we took a step back to verify that the C++ plugin’s performance was acceptable. With that confirmed, we’ll continue this week by making our programming lives easier. One pain point so far has been with exposing new Unity APIs to C++. It’s not that it’s difficult to do this, but there’s a lot of boilerplate required. That boilerplate takes time to write and it’s easy to make mistakes copying and pasting existing functions. So this week’s article introduces a code generator that will write the boilerplate for us! We’ll also reorganize the project a little so the code that supports C++ scripting is separated away from our game code. That’ll make it easy to add support for C++ scripting to any Unity project.
I continue to learn a lot by reading the C++ code that IL2CPP outputs. Like reading decompiled code, it gives some insight into what what Unity’s build process is doing with the C# we give it. This week I learned that
sizeof(MyStruct) isn’t a compile-time constant like it is in C++. Because of that, IL2CPP generates some less-than-ideal C++ code every time you use it. Today’s article shows the process I went through to work around that issue and ends up with some code you can drop into your project to avoid the problem.
C# generics are weak. The
where clause allows you to know a little about the generic (“
T“) types you’re given, but that’s just scratching the surface of what you can do with code generation. Today’s article will show you how easy it is to add a little code generation to a project and the power that brings.