Just wondering if there is any way to generate code in Unity at the moment. Don’t need any special tools, just the ability to generate a string, put it into a new file and add it to the compilation. Is this possible in 2021.2, or are there any plans for supporting it in 2022.x?
Do you need the file to disappear after compilation? Or can it stick around?
We’ve used System.CodeDom since at least Unity 2018 to generate files based on certain conditions. That file is permanent, though, although we can take it out of source control.
Yeah. The goal is generating permanent C# classes based on some conditions. Do you just generate the file with some text then, or is there more to it?
I am doing things like this (it works any current editor version): https://discussions.unity.com/t/843323/9
And they stay there until I change something in one of the localization tables, then this regenerates the corresponding code file here:
Yeah, pretty much. Just create the string and then write the file to disk.
System.CodeDom has some things that makes it a bit easier, but you could as well have used a StringBuilder.
Our specific use is making a file that contains all the layers and layer masks as const ints. We update it when we change the layer name file, so:
public class TagSavePostprocessor : UnityEditor.AssetModificationProcessor {
static string[] OnWillSaveAssets(string[] paths) {
if (Array.IndexOf(paths, "ProjectSettings/TagManager.asset") != -1)
CodeGeneration.EnsureLayersEnumUpdated();
return paths;
}
}
Though we have also run code like this in
UnityEditor.EditorApplication.playModeStateChanged, during ExitingEditMode, that works as well.