Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

C# 6.0

Discussion in 'Scripting' started by Deleted User, Mar 27, 2015.

  1. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,298
    I updated to the C# 7 version yesterday, and while it was working yesterday, today it refuses to compile but only shows a completely blank error in the console. Any ideas on what might be going on or how to narrow it down? Is there a log file anywhere that might have more info that the regular Unity editor log? I'm on Windows 10 with the new VS 2016 RC.
     
  2. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    1. Check CSharp70Support/compilation.log
    2. Do you use Unity 5.4 or 5.5?
     
  3. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,298
    Hmm nothing useful in there either. I'm using 5.5. I'll try a few things to see if I can figure out what's going on. Gotta love a completely blank console error. o_O
     
  4. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    No idea how I tested, but the Roslyn upgrade I did in v2.0.1 was actually a downgrade to some pretty old version. Will fix it right now.

    PS
    Even though I put a wrong version of Roslyn there, the console window shouldn't be blank. Mine is full of compilation errors.
     
    Last edited: Dec 6, 2016
  5. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,298
    Switching back to CS6Support instead of CS7Support seems to have fixed whatever was going on. My code didn't have any C# 7 specific stuff except for whatever was in the CSharp vNext Support folder. The blank console error makes me think that csc.exe was crashing or something and Unity didn't know what to do about it.
     
  6. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    Even if csc.exe crashes there must be some message in the console. There usually is.
     
  7. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,298
  8. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    I uploaded CSharp70Support 2.0.2.zip with the updated (for real) 7.0 compiler.

    However, now it doesn't work on Mac. Roslyn C# 7.0 throws MethodNotImplemented exception with current Mono 4.6.2.7. Mono 4.8 Alpha 5 changes it to "error CS2011: Error opening response file", not sure why.
     
  9. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,298
    That does seem to have fixed it for me. I'll try out the C# 7 version for a while and see if I have any more enigmatic errors.
     
  10. Agent766

    Agent766

    Joined:
    Nov 10, 2016
    Posts:
    3
    @alexzzzz sorry for taking a few days to get back to you. That was indeed the problem, but I'm not sure why. My SoundManager's script OnEnable is being called before the UnityScheduler initializes despite the fact that the UnityScheduler has the highest priority in the Script Execution Order.

    God dammit Unity.
     
  11. bddckr

    bddckr

    Joined:
    Sep 13, 2016
    Posts:
    26
    Hey there @alexzzzz !
    It looks like there's a problem using C# 7.0 with Unity 5.6.0b1 currently:
    I'd love to use the new beta with your project. :)
     
  12. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    @bddckr, I'm working on a fix...
     
  13. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
  14. bddckr

    bddckr

    Joined:
    Sep 13, 2016
    Posts:
    26
    It works! Thanks for fixing it and being so fast at it, too.

    (Btw: There are two zips of those latest versions now. And nice to clean up those branches. ;))
     
  15. stopiccot

    stopiccot

    Joined:
    May 2, 2013
    Posts:
    26
    Is there a way to force msc.exe compiler on OS X (so debugging with MonoDevelop works) while preserving Roslyn folder for windows guys?
     
  16. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    @stopiccot
    Not at the moment. Haven't thought about this use case.
     
  17. louisgv

    louisgv

    Joined:
    Aug 7, 2013
    Posts:
    18
    Is there any chance this hack can be made to work on Linux? I tried import it and I got the blank error...
     
  18. stoneblade

    stoneblade

    Joined:
    Apr 7, 2015
    Posts:
    5
    Compile this
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Xml.Linq;
    3.  
    4. public class Test : MonoBehaviour
    5. {
    6.     void Start()
    7.     {
    8.         var reader = XDocument.Load("hihi");
    9.     }
    10. }
    Getting this
    Code (CSharp):
    1. Assets\Test.cs(8,22): error CS0012: The type 'XmlReader' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
    Tried with CSharp60Support 2.0.3.zip CSharp70Support 2.0.3.zip
    On Window 10

    Log
    Code (CSharp):
    1. ********************************************************************************
    2. *                     Monday, January 02, 2017 2:25:12 AM                      *
    3. ********************************************************************************
    4. CSharpCompilerWrapper.exe version: 2.0.0.0
    5. Platform: Windows
    6. Target assembly: Assembly-CSharp.dll
    7. Project directory: C:\Users\stoneblade\Documents\repository\Test2
    8. Unity 'Data' or 'Frameworks' directory: C:/Program Files/Unity5.5.0f3/Editor/Data
    9. Compiler: Microsoft C# 7.0
    10.  
    11. - Compilation -----------------------------------------------
    12.  
    13. Process: C:\Users\stoneblade\Documents\repository\Test2\CSharp70Support\Roslyn\csc.exe
    14. Arguments: -nostdlib+ -noconfig -nologo -r:"C:/Program Files/Unity5.5.0f3/Editor/Data\Mono/lib/mono/2.0/mscorlib.dll" -r:"C:/Program Files/Unity5.5.0f3/Editor/Data\Mono/lib/mono/2.0/System.dll" -r:"C:/Program Files/Unity5.5.0f3/Editor/Data\Mono/lib/mono/2.0/System.Core.dll" -r:"C:/Program Files/Unity5.5.0f3/Editor/Data\Mono/lib/mono/2.0/System.Xml.dll" @Temp/UnityTempFile-e7da8649b4527484bb8c91f47bb799d5
    15. Exit code: 1
    16. Elapsed time: 1.54 sec
    17.  
    18. - Compiler output (0 lines):
    19.  
    20. - Compiler errors (1 line):
    21. 0: Assets\Test.cs(8,22): error CS0012: The type 'XmlReader' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
    Maybe because the slash before Mono is wrong?
    C:/Program Files/Unity5.5.0f3/Editor/Data\Mono/lib/mono/2.0/System.dll
     
  19. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    Unfortunately, I have zero experience in Linux. You can try to use the updated C# 6.0 compiler that comes in Unity 5.5+:
    1. Download CSharp60Support 2.0.3.zip
    2. Don't copy any files from it to your project, just install CSharp60Support.unitypackage
    3. Delete Assets/CSharp vNext Support/Editor/CSharpVNextSupport.dll - it's not needed
    4. Create a text file Assets/mcs.rsp :
    This way you should get C# 6.0 support with async/await and other stuff using the stock Unity 5.5 compiler.
     
    M_R likes this.
  20. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    This is interesting. This example doesn't compile on its own, but when I add the exact same file to an existing project, it compiles just fine. The compilation logs look identical, the backslash before Mono is not a problem.
     
  21. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    @stoneblade
    Set
    Project Settings-> Player -> Other Settings -> Api Compatibility Level = .Net 2.0

    PS
    Fixed in CSharpXXSupport 2.0.4. Should work regardless of API Compatibility Level.
     
    Last edited: Jan 1, 2017
  22. stoneblade

    stoneblade

    Joined:
    Apr 7, 2015
    Posts:
    5
    Thanks for the quick fix
    I always work in .net 2.0, but usually forgot to set it in new project
     
  23. siOnzeeCZ

    siOnzeeCZ

    Joined:
    Oct 21, 2016
    Posts:
    6
    Hi, can you add support for CsharpCodeProvider? Because compiler from .Net 2.0 | 3.5 can't parse C# 6\7.
    Compiling code like this:
    Code (CSharp):
    1. var number = 1;
    2. string message = $"This is number {number}";
    Will throw: error CS1525: Unexpected symbol `<internal>'
    Which is on line with '$' symbol.

    I think there's needed reflection for correct roslyn path. (to csc.exe)

    If you add support for it? :)
     
  24. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    Code (CSharp):
    1. using System;
    2. using System.Diagnostics;
    3. using System.IO;
    4. using System.Reflection;
    5. using UnityEngine;
    6.  
    7. public class CompilerExample : MonoBehaviour
    8. {
    9.     private string cscPath = "Roslyn/csc.exe";
    10.  
    11.     private void Start()
    12.     {
    13.         string source = @"
    14.        using UnityEngine;
    15.  
    16.        public class Test
    17.        {
    18.            public static void Foo()
    19.            {
    20.                var a = 1;
    21.                var b = 2;
    22.                Debug.Log($""{a} + {b} = {a + b}"");
    23.            }
    24.        }";
    25.  
    26.         var assembly = Compile(source, "output.dll");
    27.  
    28.         var method = assembly.GetType("Test").GetMethod("Foo");
    29.         var del = (Action)Delegate.CreateDelegate(typeof(Action), method);
    30.         del.Invoke();
    31.     }
    32.  
    33.     private Assembly Compile(string source, string assemblyName)
    34.     {
    35.         string currentDirectory = Directory.GetCurrentDirectory();
    36.         string outputFilename = Path.Combine(currentDirectory, assemblyName);
    37.         string sourceFilename = Path.Combine(currentDirectory, "source.cs");
    38.         File.WriteAllText(sourceFilename, source);
    39.  
    40.         string arguments = "\"" + sourceFilename + "\"";
    41.         arguments += " -out:\"" + outputFilename + "\"";
    42.         arguments += " -target:library";
    43.         arguments += " -nostdlib+";
    44.         foreach (var referencedAssembly in AppDomain.CurrentDomain.GetAssemblies())
    45.         {
    46.             arguments += " -r:\"" + referencedAssembly.Location + "\"";
    47.         }
    48.  
    49.         var processStartInfo = new ProcessStartInfo
    50.                                {
    51.                                    FileName = Path.Combine(currentDirectory, cscPath),
    52.                                    Arguments = arguments,
    53.                                    CreateNoWindow = true,
    54.                                    UseShellExecute = false,
    55.                                };
    56.  
    57.         var process = Process.Start(processStartInfo);
    58.         process.WaitForExit();
    59.  
    60.         int exitCode = process.ExitCode;
    61.         if (exitCode != 0)
    62.         {
    63.             throw new Exception("Compilation error");
    64.         }
    65.  
    66.         var bytes = File.ReadAllBytes(outputFilename);
    67.         var assembly = Assembly.Load(bytes);
    68.  
    69.         File.Delete(sourceFilename);
    70.         File.Delete(outputFilename);
    71.  
    72.         return assembly;
    73.     }
    74. }
     

    Attached Files:

    rakkarage and Venryx like this.
  25. stoneblade

    stoneblade

    Joined:
    Apr 7, 2015
    Posts:
    5
    On Mac new project, .Net 2.0
    Code (CSharp):
    1. Compiler redirection error: System.ComponentModel.Win32Exception
    2. ApplicationName='/Applications/Unity 5.3.6/Unity 5.3.6.app/Contents/Frameworks/Mono/lib/mono/2.0/MonoBleedingEdge/bin/mono', CommandLine='"/Users/kelvin/Documents/Repository/Unity 5.3.6/Demo/CSharp60Support/Roslyn/csc.exe" -nostdlib+ -noconfig -nologo -r:"/Applications/Unity 5.3.6/Unity 5.3.6.app/Contents/Frameworks/Mono/lib/mono/2.0/mscorlib.dll" -r:"/Applications/Unity 5.3.6/Unity 5.3.6.app/Contents/Frameworks/Mono/lib/mono/2.0/System.dll" -r:"/Applications/Unity 5.3.6/Unity 5.3.6.app/Contents/Frameworks/Mono/lib/mono/2.0/System.Core.dll" -r:"/Applications/Unity 5.3.6/Unity 5.3.6.app/Contents/Frameworks/Mono/lib/mono/2.0/System.Xml.dll" @Temp/UnityTempFile-5ce96405461d9415fa2eafc3a5429499 -debug-', CurrentDirectory=''   at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
    3.   at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
    4.   at System.Diagnostics.Process.Start () [0x00000] in <filename unknown>:0
    5.   at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:Start ()
    6.   at Compiler.Compile (Platform platform, System.String unityEditorDataDir, System.String responseFile) [0x00000] in <filename unknown>:0
    7.   at Program.Compile (System.String[] args, .Logger logger) [0x00000] in <filename unknown>:0
    8.   at Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
    Also tried Unity 5.4.2 and 5.5.0

    Log
    Code (CSharp):
    1. ********************************************************************************
    2. *                     Wednesday, 04 January 2017 11:07:03                      *
    3. ********************************************************************************
    4. CSharpCompilerWrapper.exe version: 2.0.2.27
    5. Platform: Mac
    6. Target assembly: Assembly-CSharp-firstpass.dll
    7. Project directory: /Users/kelvin/Documents/Repository/Unity 5.5.0/Demo
    8. Target profile directory: /Applications/Unity 5.5.0/Unity 5.5.0.app/Contents/Mono/lib/mono/2.0
    9. Unity 'Data' or 'Frameworks' directory: /Applications/Unity 5.5.0/Unity 5.5.0.app/Contents
    10. Compiler: Microsoft C# 6.0
    11.  
    12. - Compilation -----------------------------------------------
    13.  
    14. Process: /Applications/Unity 5.5.0/Unity 5.5.0.app/Contents/Mono/lib/mono/2.0/MonoBleedingEdge/bin/mono
    15. Arguments: "/Users/kelvin/Documents/Repository/Unity 5.5.0/Demo/CSharp60Support/Roslyn/csc.exe" -nostdlib+ -noconfig -nologo -r:"/Applications/Unity 5.5.0/Unity 5.5.0.app/Contents/Mono/lib/mono/2.0/mscorlib.dll" -r:"/Applications/Unity 5.5.0/Unity 5.5.0.app/Contents/Mono/lib/mono/2.0/System.dll" -r:"/Applications/Unity 5.5.0/Unity 5.5.0.app/Contents/Mono/lib/mono/2.0/System.Core.dll" -r:"/Applications/Unity 5.5.0/Unity 5.5.0.app/Contents/Mono/lib/mono/2.0/System.Xml.dll" @Temp/UnityTempFile-7d6a6ea0122f344768a20b253ca63cc5 -debug-
    16.  
     
  26. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
  27. stoneblade

    stoneblade

    Joined:
    Apr 7, 2015
    Posts:
    5
    macOS 10.12.1
    Unity 5.4.2f2
    .Net 2.0

    Unity Console
    Code (CSharp):
    1. Unhandled Exception:
    2. System.TypeLoadException: Could not load type 'System.Runtime.InteropServices.Marshal' from assembly 'System.Reflection.Metadata'.
    3. at Microsoft.CodeAnalysis.CommandLineArguments.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataReferenceResolver metadataResolver, System.Collections.Generic.List`1 diagnosticsOpt, Microsoft.CodeAnalysis.CommonMessageProvider messageProviderOpt, System.Collections.Generic.List`1 resolved) [0x00000] in <filename unknown>:0
    4. at Microsoft.CodeAnalysis.CommonCompiler.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataFileReferenceResolver externalReferenceResolver, Microsoft.CodeAnalysis.MetadataFileReferenceProvider metadataProvider, System.Collections.Generic.List`1 diagnostics, Microsoft.CodeAnalysis.AssemblyIdentityComparer assemblyIdentityComparer, Microsoft.CodeAnalysis.TouchedFileLogger touchedFiles, Microsoft.CodeAnalysis.MetadataFileReferenceResolver& referenceDirectiveResolver) [0x00000] in <filename unknown>:0
    5. at Microsoft.CodeAnalysis.CSharp.CSharpCompiler.CreateCompilation (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.TouchedFileLogger touchedFilesLogger, Microsoft.CodeAnalysis.ErrorLogger errorLogger) [0x00000] in <filename unknown>:0
    6. at Microsoft.CodeAnalysis.CommonCompiler.RunCore (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.ErrorLogger errorLogger, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    7. at Microsoft.CodeAnalysis.CommonCompiler.Run (System.IO.TextWriter consoleOutput, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    8. at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc+<>c__DisplayClass1_0.<Run>b__0 (System.IO.TextWriter textWriterOut, System.IO.TextWriter _) [0x00000] in <filename unknown>:0
    9. at Roslyn.Utilities.ConsoleUtil.RunWithOutput[Int32] (Boolean utf8Encoding, System.Func`3 func) [0x00000] in <filename unknown>:0
    10. at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc.Run (System.String clientDirectory, System.String sdkDirectory, System.String[] args, IAnalyzerAssemblyLoader analyzerLoader) [0x00000] in <filename unknown>:0
    11. at Microsoft.CodeAnalysis.BuildTasks.BuildClient.RunWithConsoleOutput (System.String[] args, System.String clientDir, System.String workingDir, System.String sdkDir, IAnalyzerAssemblyLoader analyzerLoader, RequestLanguage language, System.Func`5 fallbackCompiler) [0x00000] in <filename unknown>:0
    12. at Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
    13. [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'System.Runtime.InteropServices.Marshal' from assembly 'System.Reflection.Metadata'.
    14. at Microsoft.CodeAnalysis.CommandLineArguments.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataReferenceResolver metadataResolver, System.Collections.Generic.List`1 diagnosticsOpt, Microsoft.CodeAnalysis.CommonMessageProvider messageProviderOpt, System.Collections.Generic.List`1 resolved) [0x00000] in <filename unknown>:0
    15. at Microsoft.CodeAnalysis.CommonCompiler.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataFileReferenceResolver externalReferenceResolver, Microsoft.CodeAnalysis.MetadataFileReferenceProvider metadataProvider, System.Collections.Generic.List`1 diagnostics, Microsoft.CodeAnalysis.AssemblyIdentityComparer assemblyIdentityComparer, Microsoft.CodeAnalysis.TouchedFileLogger touchedFiles, Microsoft.CodeAnalysis.MetadataFileReferenceResolver& referenceDirectiveResolver) [0x00000] in <filename unknown>:0
    16. at Microsoft.CodeAnalysis.CSharp.CSharpCompiler.CreateCompilation (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.TouchedFileLogger touchedFilesLogger, Microsoft.CodeAnalysis.ErrorLogger errorLogger) [0x00000] in <filename unknown>:0
    17. at Microsoft.CodeAnalysis.CommonCompiler.RunCore (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.ErrorLogger errorLogger, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    18. at Microsoft.CodeAnalysis.CommonCompiler.Run (System.IO.TextWriter consoleOutput, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    19. at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc+<>c__DisplayClass1_0.<Run>b__0 (System.IO.TextWriter textWriterOut, System.IO.TextWriter _) [0x00000] in <filename unknown>:0
    20. at Roslyn.Utilities.ConsoleUtil.RunWithOutput[Int32] (Boolean utf8Encoding, System.Func`3 func) [0x00000] in <filename unknown>:0
    21. at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc.Run (System.String clientDirectory, System.String sdkDirectory, System.String[] args, IAnalyzerAssemblyLoader analyzerLoader) [0x00000] in <filename unknown>:0
    22. at Microsoft.CodeAnalysis.BuildTasks.BuildClient.RunWithConsoleOutput (System.String[] args, System.String clientDir, System.String workingDir, System.String sdkDir, IAnalyzerAssemblyLoader analyzerLoader, RequestLanguage language, System.Func`5 fallbackCompiler) [0x00000] in <filename unknown>:0
    23. at Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
    24. Missing method AllocHGlobal in assembly /Users/michael/Documents/repository/Test/CSharp60Support/Roslyn/System.Reflection.Metadata.dll, type System.Runtime.InteropServices.Marshal
    25.  
    compilation log
    Code (CSharp):
    1. ********************************************************************************
    2. *                      Thursday, 05 January 2017 10:42:03                      *
    3. ********************************************************************************
    4. CSharpCompilerWrapper.exe version: 2.0.3.30
    5. Platform: Mac
    6. Target assembly: Assembly-CSharp.dll
    7. Project directory: /Users/michael/Documents/repository/Test
    8. Target profile directory: /Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents/Mono/lib/mono/2.0
    9. Unity 'Data' or 'Frameworks' directory: /Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents
    10. Compiler: Microsoft C# 6.0
    11.  
    12. - Compilation -----------------------------------------------
    13.  
    14. Process: /Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents/MonoBleedingEdge/bin/mono
    15. Arguments: "/Users/michael/Documents/repository/Test/CSharp60Support/Roslyn/csc.exe" -nostdlib+ -noconfig -nologo -r:"/Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents/Mono/lib/mono/2.0/mscorlib.dll" -r:"/Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents/Mono/lib/mono/2.0/System.dll" -r:"/Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents/Mono/lib/mono/2.0/System.Core.dll" -r:"/Applications/Unity5.4.2f2/Unity5.4.2f2.app/Contents/Mono/lib/mono/2.0/System.Xml.dll" @Temp/UnityTempFile-8458ca649c14040f9891763adbe61ac7 -debug-
    16. Exit code: 1
    17. Elapsed time: 0.61 sec
    18.  
    19. - Compiler output (0 lines):
    20.  
    21. - Compiler errors (24 lines):
    22. 0: Unhandled Exception:
    23. 1: System.TypeLoadException: Could not load type 'System.Runtime.InteropServices.Marshal' from assembly 'System.Reflection.Metadata'.
    24. 2: at Microsoft.CodeAnalysis.CommandLineArguments.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataReferenceResolver metadataResolver, System.Collections.Generic.List`1 diagnosticsOpt, Microsoft.CodeAnalysis.CommonMessageProvider messageProviderOpt, System.Collections.Generic.List`1 resolved) [0x00000] in <filename unknown>:0
    25. 3: at Microsoft.CodeAnalysis.CommonCompiler.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataFileReferenceResolver externalReferenceResolver, Microsoft.CodeAnalysis.MetadataFileReferenceProvider metadataProvider, System.Collections.Generic.List`1 diagnostics, Microsoft.CodeAnalysis.AssemblyIdentityComparer assemblyIdentityComparer, Microsoft.CodeAnalysis.TouchedFileLogger touchedFiles, Microsoft.CodeAnalysis.MetadataFileReferenceResolver& referenceDirectiveResolver) [0x00000] in <filename unknown>:0
    26. 4: at Microsoft.CodeAnalysis.CSharp.CSharpCompiler.CreateCompilation (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.TouchedFileLogger touchedFilesLogger, Microsoft.CodeAnalysis.ErrorLogger errorLogger) [0x00000] in <filename unknown>:0
    27. 5: at Microsoft.CodeAnalysis.CommonCompiler.RunCore (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.ErrorLogger errorLogger, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    28. 6: at Microsoft.CodeAnalysis.CommonCompiler.Run (System.IO.TextWriter consoleOutput, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    29. 7: at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc+<>c__DisplayClass1_0.<Run>b__0 (System.IO.TextWriter textWriterOut, System.IO.TextWriter _) [0x00000] in <filename unknown>:0
    30. 8: at Roslyn.Utilities.ConsoleUtil.RunWithOutput[Int32] (Boolean utf8Encoding, System.Func`3 func) [0x00000] in <filename unknown>:0
    31. 9: at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc.Run (System.String clientDirectory, System.String sdkDirectory, System.String[] args, IAnalyzerAssemblyLoader analyzerLoader) [0x00000] in <filename unknown>:0
    32. 10: at Microsoft.CodeAnalysis.BuildTasks.BuildClient.RunWithConsoleOutput (System.String[] args, System.String clientDir, System.String workingDir, System.String sdkDir, IAnalyzerAssemblyLoader analyzerLoader, RequestLanguage language, System.Func`5 fallbackCompiler) [0x00000] in <filename unknown>:0
    33. 11: at Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
    34. 12: [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'System.Runtime.InteropServices.Marshal' from assembly 'System.Reflection.Metadata'.
    35. 13: at Microsoft.CodeAnalysis.CommandLineArguments.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataReferenceResolver metadataResolver, System.Collections.Generic.List`1 diagnosticsOpt, Microsoft.CodeAnalysis.CommonMessageProvider messageProviderOpt, System.Collections.Generic.List`1 resolved) [0x00000] in <filename unknown>:0
    36. 14: at Microsoft.CodeAnalysis.CommonCompiler.ResolveMetadataReferences (Microsoft.CodeAnalysis.MetadataFileReferenceResolver externalReferenceResolver, Microsoft.CodeAnalysis.MetadataFileReferenceProvider metadataProvider, System.Collections.Generic.List`1 diagnostics, Microsoft.CodeAnalysis.AssemblyIdentityComparer assemblyIdentityComparer, Microsoft.CodeAnalysis.TouchedFileLogger touchedFiles, Microsoft.CodeAnalysis.MetadataFileReferenceResolver& referenceDirectiveResolver) [0x00000] in <filename unknown>:0
    37. 15: at Microsoft.CodeAnalysis.CSharp.CSharpCompiler.CreateCompilation (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.TouchedFileLogger touchedFilesLogger, Microsoft.CodeAnalysis.ErrorLogger errorLogger) [0x00000] in <filename unknown>:0
    38. 16: at Microsoft.CodeAnalysis.CommonCompiler.RunCore (System.IO.TextWriter consoleOutput, Microsoft.CodeAnalysis.ErrorLogger errorLogger, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    39. 17: at Microsoft.CodeAnalysis.CommonCompiler.Run (System.IO.TextWriter consoleOutput, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0
    40. 18: at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc+<>c__DisplayClass1_0.<Run>b__0 (System.IO.TextWriter textWriterOut, System.IO.TextWriter _) [0x00000] in <filename unknown>:0
    41. 19: at Roslyn.Utilities.ConsoleUtil.RunWithOutput[Int32] (Boolean utf8Encoding, System.Func`3 func) [0x00000] in <filename unknown>:0
    42. 20: at Microsoft.CodeAnalysis.CSharp.CommandLine.Csc.Run (System.String clientDirectory, System.String sdkDirectory, System.String[] args, IAnalyzerAssemblyLoader analyzerLoader) [0x00000] in <filename unknown>:0
    43. 21: at Microsoft.CodeAnalysis.BuildTasks.BuildClient.RunWithConsoleOutput (System.String[] args, System.String clientDir, System.String workingDir, System.String sdkDir, IAnalyzerAssemblyLoader analyzerLoader, RequestLanguage language, System.Func`5 fallbackCompiler) [0x00000] in <filename unknown>:0
    44. 22: at Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
    45. 23: Missing method AllocHGlobal in assembly /Users/michael/Documents/repository/Test/CSharp60Support/Roslyn/System.Reflection.Metadata.dll, type System.Runtime.InteropServices.Marshal
    46.  
     
  28. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
  29. stoneblade

    stoneblade

    Joined:
    Apr 7, 2015
    Posts:
    5
    Installed Mono on Mac and it work

    Too bad I couldn't use it like this, cannot force everyone in my company to install Mono on their mac
    I use Window myself
     
  30. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    If you are ok with using Mono 6.0 compiler instead of Roslyn (don't see much difference really), you can just delete Roslyn folder from CSharp60Support and Mono compiler will be used automatically.
     
  31. stopiccot

    stopiccot

    Joined:
    May 2, 2013
    Posts:
    26
    I'm getting:
    Code (csharp):
    1. Assets/CSharp vNext Support/AsyncTools/AsyncTools.cs(13,29): error CS0433: The imported type `System.Lazy<T>' is defined multiple times
    error when using Unity 5.6b4
     
  32. MNNoxMortem

    MNNoxMortem

    Joined:
    Sep 11, 2016
    Posts:
    358
    Hello!

    When i use the c#6 bridge I get the following error:
    NullReferenceException: Object reference not set to an instance of an object
    UnityScheduler.LateUpdate () (at Assets/CSharp vNext Support/AsyncTools/UnityScheduler.cs:65)
    NullReferenceException: Object reference not set to an instance of an object
    UnityScheduler.Update () (at Assets/CSharp vNext Support/AsyncTools/UnityScheduler.cs:63)
    And when i click it it highlights the following line of code in visual studio:
    private void FixedUpdate() => FixedUpdateScheduler.Activate();​

    Any ideas or how to debug this?
     
  33. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    @MNNoxMortem
    When do you get these errors?

    @stopiccot
    Update to the latest version of CSharpXXSupport.
     
  34. sebas77

    sebas77

    Joined:
    Nov 4, 2011
    Posts:
    854
    do you reckon this compiler could enable external profilers to profile c# dll made with it? If so, how do you do it?
     
  35. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    @sebas77
    The problem with using the external profilers to profile C# written for Unity, is that this C# usually heavily depends on Unity API that won't work without Unity engine itself.

    You can profile the code that references UnityEngine.dll but uses only its managed parts. Most of the vector math is managed and works fine under external profilers, but Vector3.SmoothDamp, for example, is implemented in native code and will crash if run outside of Unity. There's nothing we can do.
     
  36. sebas77

    sebas77

    Joined:
    Nov 4, 2011
    Posts:
    854
    huh, interesting, I actually can profile the native code, using Glowcode or Vtune, however both tools support mixed profiling (managed/native application), but they can't detect the .net layer. IMO the reason being that Unity doesn't actually use a .net CLR, but instead uses mono, that is not understood by those programs.
    So my question wasn't about profiling with Unity, but profiling with .net profilers.
     
  37. ReadyPlayGames

    ReadyPlayGames

    Joined:
    Jan 24, 2015
    Posts:
    41
    Hello! I am trying to port a piece of code that's using ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion) from Threading. Unfortunately, it's throwing a NotImplementedException: "recursionPolicy != NoRecursion not currently implemented". What do I do? Is there a non-recursion alternative to "EnterReadLock" and such? I feel like I'm so close! Thank you very much for this awesome tool!

    I tried the 6 and the 7 versions.

    Edit: For those in the same boat, I ended up using this as a workaround: https://readerwriterlockalt.codeplex.com/
     
    Last edited: Feb 3, 2017
  38. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    I hope, not that many people use
    Code (CSharp):
    1. await AsyncTools.ToUpdate();
    2. await AsyncTools.ToFixedUpdate();
    3. await AsyncTools.ToLateUpdate();
    because the latest Mono Runtime Updrage Preview has only one synchronization context for the main thread.
     
  39. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,318
    Wow. Just stumbled on this thread. So, can anyone confirm, would you use this great tool for actual production jobs?
    ie if there are certain C# 6 features you really want to use and you compile using CSharpXXX, how crash proof will the install be? Also, are Async methods still unsupported?
     
    Last edited: Feb 4, 2017
  40. ReadyPlayGames

    ReadyPlayGames

    Joined:
    Jan 24, 2015
    Posts:
    41
    Edit: We were using 5.3.3, upgrading Unity to 5.5.1 solved this problem! Huzzah!

    After finding my way around, everything was fine, until it came time to put it on a Mac. Now the editor comes up with the error: "Failure generating network code. UnityEditor.Scripting.Serialization.Weaver:WeaveUnetFromEditor(String, String, String, String, Boolean)" along with another (much longer) error:

    Code (csharp):
    1.  
    2. UNetWeaver error: Exception :System.NullReferenceException: Object reference not set to an instance of an object
    3.  
    4. at Unity.UNetWeaver.Weaver.Weave (System.String assName, IEnumerable`1 dependencies, IAssemblyResolver assemblyResolver, System.String unityEngineDLLPath, System.String unityUNetDLLPath, System.String outputDir) [0x00220] in /Users/builduser/buildslave/unity/build/Extensions/Networking/Weaver/UNetWeaver.cs:1727
    5.  
    6. at Unity.UNetWeaver.Weaver.WeaveAssemblies (IEnumerable`1 assemblies, IEnumerable`1 dependencies, IAssemblyResolver assemblyResolver, System.String outputDir, System.String unityEngineDLLPath, System.String unityUNetDLLPath) [0x00062] in /Users/builduser/buildslave/unity/build/Extensions/Networking/Weaver/UNetWeaver.cs:1748
    7.  
    8. UnityEngine.Debug:LogError(Object)
    9.  
    10. Unity.UNetWeaver.Log:Error(String) (at /Users/builduser/buildslave/unity/build/Extensions/Networking/Weaver/Program.cs:20)
    11.  
    12. Unity.UNetWeaver.Weaver:WeaveAssemblies(IEnumerable`1, IEnumerable`1, IAssemblyResolver, String, String, String) (at /Users/builduser/buildslave/unity/build/Extensions/Networking/Weaver/UNetWeaver.cs:1755)
    13.  
    14. Unity.UNetWeaver.Program:Process(String, String, String, String[], String[], IAssemblyResolver, Action`1, Action`1) (at /Users/builduser/buildslave/unity/build/Extensions/Networking/Weaver/Program.cs:34)
    15.  
    16. UnityEditor.Scripting.Serialization.Weaver:WeaveUnetFromEditor(String, String, String, String, Boolean)
    17.  
    Works on Windows though. I'm not sure what's happening. I installed Mono on the mac, downloaded the C# 7 .zip (2.0.5), followed all of the directions, but the Mac isn't having it.

    I should point out that the Unity project itself is not using UNet (it connects to the web via WWW class for basic stuff).
     
    Last edited: Feb 6, 2017
  41. Vancete

    Vancete

    Joined:
    May 3, 2010
    Posts:
    173
    This thread is confusing, is there any list of benefits of using this instead of the 'legacy' one? Just curious.
     
  42. radicalEd

    radicalEd

    Joined:
    Mar 19, 2016
    Posts:
    81
    If you're good at programming, massively improved workflow, neater code, and (I believe, I have yet to try it myself) access to features such as the dynamic keyword.

    Stuff like
    Code (csharp):
    1. foo?.bar():
    vs

    Code (csharp):
    1. if (foo != null) foo.bar();
     
    rakkarage likes this.
  43. Vancete

    Vancete

    Joined:
    May 3, 2010
    Posts:
    173
    With 'confusing' I was meaning long to read and hard to find where that is explained :p

    Thanks
     
  44. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    Try to delete Roslyn folder from CSharp60Support. The plugin will switch to using Mono C# 6 compiler instead. Roslyn doesn't generate debug symbols on Mac. Usually it just makes it impossible to debug code on Mac, but maybe debug symbols are used in Unity for something else as well.

    If you want C# 7.0, unfortunately these's no Mono C# 7 compiler and, I guess, will never be.
     
  45. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    I won't say anything about production readiness since I haven't published anything myself. I'll just write a quick summary. There are/were a bunch of issues with this project that can be split into several categories:

    1. Integration issues.

    - Unity does some internal changes from time to time, that break the compatibility with my plugin. I track all the betas and fix the issues as soon as I see them. However, I can miss issues on Mac OS or when some older version (like 5.4.x) updates. It may stay unfixed until someone brings it to my attention.

    - Not obvious edge cases. There were a bunch that I fixed. Maybe, there are more that I'm not aware of.

    If I get hit by a bus, you or someone else will have to fix the problems yourselves.

    2. Compatibility issues with code written for the "real" Net Framework 4+.

    Some C# 5-7 features are purely compiler features; expression bodied members in C# 6, for example. They just work. Some features require special types to exist in the CLR to make these features work. Namely:
    - Caller info attributes
    - Async/await
    - Tasks and everything related
    - A small subset of string interpolation functionality
    - Tuples

    Luckily, these types don't have to exist inside mscorlib.dll, which we don't want to mess with. They can be provided separately. For Tasks I use an old version of Task Parallel Library, that includes almost all the Task-related stuff that is needed. For async/await and caller info attributes I use AsyncBridge library, which also adds some (not all, I guess) pieces missing in the Task Parallel Library. For example, the Task class there doesn't have Task.Delay() method, but AsyncBridge contains TaskEx class that adds the missing methods.

    Types that are needed for the full string interpolation support and tuples I provide in sources.

    It's important to keep in mind, that while your code, exploiting the latest C# features, may work absolutely fine, it may work not the same way it would work under the real Net Framework 4+ or the latest Mono.

    There are also features of C# / Net Framework 4+ that won't work at all:
    - Dynamic typing (needs a ton of special types, it's just impossible to backport them all to our ancient Mono)
    - [MethodImpl(MethodImplOptions.AggressiveInlining)] attribute (needs support from JIT)
    - some others maybe

    If you drop some external C# 4+ code into your project, there's no guarantee it will compile and run smoothly.

    3. Compatibility issues with Unity and the platforms that Unity targets.

    Since Unity doesn't officially support C# 4+, of course there are compatibility issues. The known ones are described here: https://bitbucket.org/alexzzzz/unity-c-5.0-and-6.0-integration/overview

    No idea whether my hack works on XBox (probably not) / PlayStation or less mainstream platforms, but if you are targeting them, I believe you are serious people and won't let your product depend on a third-party hack from some random guy from the internets.

    4. Future issues that will arise when Unity will have upgraged to Mono 4.6+ officially and you will be trying to upgrade your projects to run there.

    Two main points here:

    - You'll have to make some obvious changes due to API differences. Like, you'll have to change all TaskEx.Delay() calls to the proper Task.Delay(), TaskEx.Start() to Task.Start(), maybe something else. This is basically Find'n'Replace kind of changes.

    - There will be difference (maybe big) in how async/await stuff works now in my demo project and how it will work in future versions of Unity.

    Async/await don't just magically work everywhere. While 'await' doesn't necessarily obliged to bring the execution back to the thread where the asynchronous task has been started, this is useful and somewhat expected. In order to make it this way, the "application frameworks" (let's call it this way) have to provide synchronization contexts for their special threads. WinForms and WPF application provide synchronization contexts for their main/UI threads. Console application don't and when you start a task asynchronously and await it, there's no guarantee the execution continue in the exact same thread from where it has been started.

    In my demo project I ended up with three synchronization contexts for the main thread: for Update, LateUpdate and FixedUpdate contexts. The latest Unity Mono Runtime Upgrade Preview has one single synchronization context for the main thread. So, if you heavily rely on

    await AsyncTools.ToUpdate();
    await AsyncTools.ToLateUpdate();
    await AsyncTools.ToFixedUpdate();

    you are doomed. :)
    (Maybe not, not sure, have to investigate further how to simulate this functionality in that preview build.)

    If you use async/await to start a task and when it finishes just to return back to the main thread no matter in which moment exactly (or don't even care about the main thread), then you'll probably won't even notice the difference after the upgrade.
     
    Last edited: Feb 6, 2017
  46. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,403
    I'm wondering, how many times do I have to reread the previous post to fix all the stupid mistakes and mistypes, not to mention the grammar. :)
     
    Qbit86 likes this.
  47. DavidSWu

    DavidSWu

    Joined:
    Jun 20, 2016
    Posts:
    113
    We are using it for a production game and so far it has been working excellently. We are not targeting Xbox or Playstation however, and I have not yet tried IL2CPP for our Android build.

    Great Work Alexzzz!

    David Wu
     
  48. Agent766

    Agent766

    Joined:
    Nov 10, 2016
    Posts:
    3
    What's the status of WebGL support? I use async/await quite liberally and I use Task.Factory.StartNew to start tasks without blocking the current method. I'm just using the given synchronization contexts and not explicitly using parallel threads. Would this cause issues when building for WebGL?
    (I'm having some weird issues when building and I'm not sure if the C# 6 asset is the cause.)
     
  49. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I'm guessing so because Unity WebGL doesn't currently support multithreading.
     
  50. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,298
    @alexzzzz Hey I'm trying to wrap my head around AsyncTools. Could you give me an example of how you'd convert a coroutine like this to use async/await instead? I can't change the StartTheThing method to async because it's in a library.

    Code (csharp):
    1. //called from a UI button via UnityEvent in the inspector
    2. public void OnButtonClicked() {
    3.   StartCoroutine(DoTheThing());
    4. }
    5.  
    6. public IEnumerator DoTheThing() {
    7.   something.StartTheThing();
    8.   while (!something.IsDone) {
    9.     yield return null;
    10.   }
    11.   DoStuffThatNeedsTheMainThread();
    12. }
    I changed it to this:
    Code (csharp):
    1. public void OnButtonClicked() {
    2.   DoTheThing().Start(UnityScheduler.UpdateScheduler);
    3. }
    4.  
    5. public async Task DoTheThing() {
    6.   something.StartTheThing();
    7.   while (!something.IsDone) {
    8.     await TaskEx.Delay(0);
    9.   }
    10.   DoStuffThatNeedsTheMainThread();
    11. }
    Is this correct? Does DoStuffThatNeedsTheMainThread get called on the main thread? Is there a better way?