Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Source Generation. Is it possible?

Discussion in '2021.2 Beta' started by Nexer8, Oct 8, 2021.

  1. Nexer8

    Nexer8

    Joined:
    Dec 10, 2017
    Posts:
    271
    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?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,177
    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.
     
    LeonhardP and Nexer8 like this.
  3. Nexer8

    Nexer8

    Joined:
    Dec 10, 2017
    Posts:
    271
    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?
     
  4. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,768
    I am doing things like this (it works any current editor version): https://forum.unity.com/threads/gen...-per-localization-table.1119829/#post-7211053

    And they stay there until I change something in one of the localization tables, then this regenerates the corresponding code file here:
    screenshot.png
     
    Last edited: Oct 8, 2021
    LeonhardP and Nexer8 like this.
  5. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,177
    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:

    Code (csharp):
    1.  
    2. public class TagSavePostprocessor : UnityEditor.AssetModificationProcessor {
    3.  
    4.     static string[] OnWillSaveAssets(string[] paths) {
    5.  
    6.         if (Array.IndexOf(paths, "ProjectSettings/TagManager.asset") != -1)
    7.             CodeGeneration.EnsureLayersEnumUpdated();
    8.  
    9.         return paths;
    10.     }
    11. }
    12.  
    Though we have also run code like this in
    UnityEditor.EditorApplication.playModeStateChanged, during ExitingEditMode, that works as well.
     
    Last edited: Oct 8, 2021
    EZaca, LeonhardP and Nexer8 like this.