Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

C# Compiler "Init Only Setter" not working in 2021.2?

Discussion in 'Experimental Scripting Previews' started by Neonlyte, Jan 10, 2022.

  1. Neonlyte

    Neonlyte

    Joined:
    Oct 17, 2013
    Posts:
    516
    I'm on version 2021.2.7, and in the documentation, I noticed that "Init Only Setter" was not listed as an unsupported C# feature:
    https://docs.unity3d.com/2021.2/Documentation/Manual/CSharpCompiler.html

    I tried using it on one property, and I was hit with CS0518:
    "Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported"

    Maybe I missed related info somewhere else on the forum, but does this feature actually work in my Unity version?
     
  2. Neonlyte

    Neonlyte

    Joined:
    Oct 17, 2013
    Posts:
    516
  3. JoshPeterson

    JoshPeterson

    Unity Technologies

    Joined:
    Jul 21, 2014
    Posts:
    6,930
    Yes, this is an unfortunate limitation. We're working on updated the documentation to explain this now.
     
    ViktorFuchadzhy and Neonlyte like this.
  4. icepower2012

    icepower2012

    Joined:
    Jan 14, 2015
    Posts:
    7
    Code (CSharp):
    1.  
    2. // Add this magic code, you will be able to use record and init.
    3. // I only tested in editor, not sure whether it would work on other platforms.
    4. namespace System.Runtime.CompilerServices
    5. {
    6.     class IsExternalInit
    7.     {
    8.      
    9.     }
    10. }
    11.  
    12. public record TestRecord(string Name, int Age);
    13.  
    14. public class Persion
    15. {
    16.     public int Age
    17.     {
    18.         get;
    19.         init;
    20.     }
    21. }
    22.  
    23.  
     
  5. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    284
    Thanks @icepower2012, it did work well for both Editor and Android build.