Search Unity

C# 6.0

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

  1. timintal

    timintal

    Joined:
    Jul 23, 2012
    Posts:
    8
    I have an issue with unity 5.6. As soon as I import C# 6.0 support into my project all log errors has no line number where exactly in script this error occured.
    Before importing:

    After importing:

    Is there a way to fix this as it really slows development process?
     
  2. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Usually async/await code looks simpler than one using coroutines. I would rewrite it this way:
    Code (CSharp):
    1. public async void OnButtonClicked() // async methods work fine as direct event handlers
    2. {
    3.     something.StartTheThing();
    4.     while (something.IsDone == false)
    5.     {
    6.         await 0;
    7.     }
    8.     DoStuffThatNeedsTheMainThread(); // will run in the main thread
    9. }
    However, if StartTheThing() returns UnityEngine.AsyncOperation, it can be even simplier:
    Code (CSharp):
    1. public async void OnButtonClicked()
    2. {
    3.     await something.StartTheThing();
    4.     DoStuffThatNeedsTheMainThread(); // will run in the main thread
    5. }
    If it returns something else, other than void, it's possible to write an awaiter for that return type so that the previous example could also work. It's also possible to write an awaiter for the type of that 'something' itself, if it would make sense. So we could write
    Code (CSharp):
    1. public async void OnButtonClicked()
    2. {
    3.     something.StartTheThing();
    4.     await something;
    5.     DoStuffThatNeedsTheMainThread(); // will run in the main thread
    6. }
    Such an awaiter wouldn't be much different from the AsyncOperationAwaiter that you can find inside AsyncTools.cs.
     
    Last edited: Apr 21, 2017
    DonLoquacious and makeshiftwings like this.
  3. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    There must be something wrong with debug symbols. Are you on Mac or Windows?
     
  4. timintal

    timintal

    Joined:
    Jul 23, 2012
    Posts:
    8
    I'm on Mac, and my colleague on Windows doesn't have this problem. May be something wrong with Mono.
     
  5. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    You must be using Roslyn compiler. Roslyn can't generate debug symbols in 'pdb' format on Mac, and the 'portable pdb', that it can generate, is not supported yet by Mono. So the solution is to switch to Mono C# 6 compiler via deleting the Roslyn folder.
     
  6. buistvo

    buistvo

    Joined:
    Apr 21, 2017
    Posts:
    1
    Great work with that pack!
    I have a problem: VS2017 compiles my code but unity not. Is says:

    Assets\CSharp vNext Support\AsyncTools\AsyncTools.cs(13,29): error CS0433: The type 'Lazy<T>' exists in both 'System.Threading, Version=1.0.2856.102, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'nunit.framework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb'

    anyone knows how to fix this?
     
    Last edited: Apr 21, 2017
  7. Qbit86

    Qbit86

    Joined:
    Sep 2, 2013
    Posts:
    487
  8. Vedrit

    Vedrit

    Joined:
    Feb 8, 2013
    Posts:
    514
    Wait, I thought C# 6.0 support wouldn't be included until Unity 2017
     
  9. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    @alexzzzz I've been using this for a while but decided to check out the new Unity beta with .NET 4.6 support, but they only support C# 6. Do you know if it's possible to use this with the new Unity runtime so that I can use both C# 7 and .NET 4 libraries like some sort of madman?
     
    Qbit86 likes this.
  10. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    I'm currently kind of out of business for a while and won't be able to test 2017.1 beta for at least a week, maybe two.

    Theoretical we should be able to use Roslyn to compile C# 7.0 for the new runtime, we just need to switch the compiler options to target CLR 4 instead of CLR 2. TPL and AsyncBridge libraries won't be needed anymore. The only thing the new Unity runtime lacks for full C# 7 support is ValueTuple type, but now we can take and use its official version from NuGet.
     
    mdrotar likes this.
  11. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Sweet. For now I've undid my tuples and out var's and went back to boring old C# 6 so I can be more "official" in my testing of the 2017.1 beta. It's exciting to see that after years of grueling effort, the Unity team is finally almost near the point of matching what you threw together one day just to see if it was possible. ;)
     
    Qbit86 likes this.
  12. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    I'm wondering, does it make sense to write C# 7.x code in Unity 2017 beta still targeting the old Mono 2.x? Shouldn't living on the edge forbid such compromises?
     
  13. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    C# 7.0 support for Unity 2017.1 / Mono 4.6

    [link removed]

    I removed Task Parallel Library and Async Bridge, and also removed my custom UnitySyncronizationContext as well as UnityTaskScheduler.

    Since Unity has only one SynchronizationContext for the main thread, stuff like this no longer works:
    Code (CSharp):
    1. await AsyncTools.ToUpdate();
    2. await AsyncTools.ToLateUpdate();
    3. await AsyncTools.ToFixedUpdate();
    Now there are only two options left:
    Code (CSharp):
    1. await AsyncTools.ToThreadPool();
    2. await AsyncTools.ToMainThread();
    I had to change the implementation of custom awaiters for UnityEngine.AsyncOperation and for floats/integers, they also work now:
    Code (CSharp):
    1. await .5f; // wait 0.5 seconds
    2. await 2; // wait 2 seconds
    3. await 0; // wait for the next frame
    4.  
    5. var request = UnityWebRequest.Get("http://placeimg.com/512/512");
    6. await request.Send(); // awaits the completion
     
    Last edited: Jun 7, 2017
  14. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    I believe I included demo scripts and maybe even scenes in the previous package ― it wasn't intentional.

    https://bitbucket.org/alexzzzz/unity-c-5.0-and-6.0-integration/downloads/CSharp70Support 3.1.0 (for Net 4.6).zip

    I've finally more or less cleaned up the mess after migrating to the new runtime. All the obsolete stuff is removed:
    1. AsyncBridge
    2. Task Parallel Library
    3. TupleBridge (replaced with the official NuGet package)
    4. Roslyn C# 6.0 support (feels obsolete now when 7.0 is available)
    5. Standalone Mono C# 6.0 support (since it's already integrated in Unity 5.5+)

    Also checked all the language feature tests in the demo project in the repository and added a couple of missing tests to cover the final C# 7.0 feature changes. Everything seem to work fine except
    1. Resharper claims that interpolated strings can't be converted to FormattableString type, however the compiler doesn't agree.
    2. I haven't tried ValueTasks yet.
     
    Last edited: Jun 8, 2017
  15. ccklokwerks

    ccklokwerks

    Joined:
    Oct 21, 2014
    Posts:
    62
    Well, I'm feeling rather stupid, so maybe someone can point out what I have done wrong.

    I'm on Mac with 2017.1.0b8, I installed the Mono framework, copied the folder parallel to Assets and imported the package.

    I wrote a test MonoBehavior which tries to do this in start, where obj is a SerializeField which is not set.

    void Start()
    {
    Transform t = this.obj?.transform;
    Debug.Log(t); ​
    }

    In the Unity editor, I don't get compile errors, but when I run, I get an unassigned reference exception. If this is working correctly, shouldn't t be assigned null?

    Also, and here you can laugh at me, but MonoDevelop-Unity is saying it doesn't support 4.6 nor langversion 7. I'm guessing I can't use MonoDevelop with this?
     
  16. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    Did you change the target .Net framework to 4.5 (or 4.6, I forget) in your project settings?
     
    ccklokwerks likes this.
  17. ccklokwerks

    ccklokwerks

    Joined:
    Oct 21, 2014
    Posts:
    62
    Yes, I did do that... I'm going to go do that in a separate test project because (presumably) MonoDevelop should not be complaining about 4.6. edit: Same behavior, so I screwed up my 2017 beta install or something... edit2: I needed to separately get the prototype MonoDevelop!
     
    Last edited: Jun 9, 2017
  18. Artery

    Artery

    Joined:
    May 30, 2017
    Posts:
    1
    @alexzzzz Awesome job! Thank you very much for your work, that's exactly what I needed!
     
  19. MNNoxMortem

    MNNoxMortem

    Joined:
    Sep 11, 2016
    Posts:
    723
    @alexzzzz
    • I removed the old "Assets\CSharp vNext Support" Folder in unity.
    • Then downloaded "CSharp70Support 3.1.0 (for Net 4.6).zip" from your bitbucket download page.
    • I tried to install .net 4.6 (NDP462-KB3151802-Web) but it told me I already have a newer version.
    • I did use the "ngen install.cmd"
    • I have set player settings -> .NET 2.0
    • I have used "Reimport All" and also restarted unity (5.6.0p3)
    • I am on Windows 10 x64
    Now I get a lot of compilation errors inside of the CSharp vNext Project:
    • Assets/CSharp vNext Support/AsyncTools/AsyncTools.cs(35,15): error CS1644: Feature `interpolated strings' cannot be used because it is not part of the C# 4.0 language specification
    • Assets/CSharp vNext Support/AsyncTools/AsyncTools.cs(46,36): error CS1644: Feature `expression bodied members' cannot be used because it is not part of the C# 4.0 language specification
    • Assets/Loader/OPCParser.cs(126,93): error CS1644: Feature `null propagating operator' cannot be used because it is not part of the C# 4.0 language specification
    And those 3 errors several times. Where did I do wrong?

    Best Wishes

    1. Edit: CSharp70Support 2.0.5.zip seems to work.
    2. Edit2: I am not able to click on error message anymore to open them directly in Rider. (Ok this looks like to be more of a problem with Rider.... Works after a restart.)

    1. Edit3: I get another error in Rider: "Ambigous Reference System.Threading.Task, System.Threading.Task" and it asks me if I want to use Task from System.Threading or from mscorlib.
    2. Fixed by manually deleting System.Threading from the References View in Rider.
    3. Edit4: After adding the import again it obviously adds the reference again and it is ambigous again. Any ideas?
    Edit 5: When building from command line I get

    ArgumentException: The Assembly System.Runtime is referenced by System.ValueTuple ('Assets/CSharp vNext Support/System.ValueTuple.dll'). But the dll is not allowed to be included or could not be found.
    at UnityEditor.AssemblyHelper.AddReferencedAssembliesRecurse (System.String assemblyPath, System.Collections.Generic.List`1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache, BuildTarget target) [0x00245] in C:\buildslave\unity\build\Editor\Mono\AssemblyHelper.cs:142
    at UnityEditor.AssemblyHelper.FindAssembliesReferencedBy (System.String[] paths, System.String[] foldersToSearch, BuildTarget target) [0x0001e] in C:\buildslave\unity\build\Editor\Mono\AssemblyHelper.cs:179

    Sounds bad. Is this harmless - if not, what do I have to do to fix it? When I try to run the generated player.exe it tells me there is no player_Data folder next to it (but there is) and in other Threads I have found that a missing dll can be the reason so this two problems look connected to me.

    Edit6: And the following warnings:
    Assets\CSharp vNext Support\TupleBridge\ValueTuple.cs(289,22): warning CS0436: The type 'ValueTuple<T1>' in '<...>\Assets/CSharp vNext Support/TupleBridge/ValueTuple.cs' conflicts with the imported type 'ValueTuple<T1>' in 'System.ValueTuple, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. Using the type defined in '<...>\Assets/CSharp vNext Support/TupleBridge/ValueTuple.cs'.
     
    Last edited: Jun 30, 2017
  20. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    https://bitbucket.org/alexzzzz/unit...loads/CSharp70Support 3.2.3 (for Net 4.6).zip

    - Unity 2017.1 and 2017.2 beta support
    - Updated C# compiler to version 2.3.1.61919
    - C# compiler version is written to the log file
    - Added C# 7.1 feature tests
    - Replaced System.ValueTuple.dll with a custom version that doesn't reference anything except System.dll and System.Core.dll

    Tested in standalone builds and in the editor on Windows (2017.1 and 2017.2), and on MacOS in (2017.1)
     
    Last edited: Jul 22, 2017
    Le_Tai likes this.
  21. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    CSharp70Support x.x.x (for Net 4.6).zip is for Unity 2017.x with built-in Net 4.6 support.
     
  22. MNNoxMortem

    MNNoxMortem

    Joined:
    Sep 11, 2016
    Posts:
    723
    Oh. Sorry. Did not see that :) Thank you so much for the library and your support here!
     
  23. OswaldHurlem

    OswaldHurlem

    Joined:
    Jan 6, 2017
    Posts:
    40
    I get constant crashes when I try to debug Unity while it's using the Experimental 4.6 Equivalent run-time. Tried updating to 2017.2 beta and VS 15.4 Preview but no dice.
    There's a bug for this https://issuetracker.unity3d.com/is...-debugging-with-vs2017-when-using-net-4-dot-6

    I'm gonna try using this and targeting the old run-time. I request that you don't abandon support for the old runtime until the new runtime stabilizes a bit.
     
  24. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    909
    Amazing

    any way to get net.3.5 for 2017.2.b



    Sequence contains no matching element
    UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline(EditorScriptCompilationOptions, BuildTargetGroup, BuildTarget)
     
  25. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Nope. We're livin' on the edge.
     
    Qbit86 likes this.
  26. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    I took a break and didn't touch Unity for a while. It seems they have changed something during 2017.2 betas and now in 2017.2.0f3 my current compiler integration mechanism no longer works. I haven't found the exact reason yet, but I guess it somehow related to the introduction of custom assemblies and assembly definition files.
     
    Qbit86 likes this.
  27. Ghopper21

    Ghopper21

    Joined:
    Aug 24, 2012
    Posts:
    170
    Hey @alexzzzz -- thanks for the update!

    Stupid question time: what's the relation of this plugin with Unity's newly launched native support for C#6? Which parts of the plugin (if any) are obsolete and which still go beyond what Unity now has built in?
     
  28. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    It lets use Roslyn instead of Mono's compiler, that means we can use the latest version of C# which is 7.1 right now.

    If there's no need in C# greater than 6.0, the whole plugin is obsolete, it's safer not to use it.
     
  29. Ghopper21

    Ghopper21

    Joined:
    Aug 24, 2012
    Posts:
    170
    Gotcha, thanks for the clear guidance @alexzzzz. And let me take this moment to say THANK YOU for the plugin, which has been a huge help to us (had to integrate some APIs that required C# 6.0, so it wasn't just a matter of preference). If you are ever in NYC, please let me buy you a drink or three.
     
    MaxEden and Qbit86 like this.
  30. MNNoxMortem

    MNNoxMortem

    Joined:
    Sep 11, 2016
    Posts:
    723
    @alexzzzz (without using the plugin - at least not in this program) unity always resets the target version for the .csproj files back to 4.5 when it should be 4.6, which is so extremly annoying. As your plugin supports c# 7.1, I thought you might have solved that, and could share how you did, if so :(
     
  31. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
  32. MNNoxMortem

    MNNoxMortem

    Joined:
    Sep 11, 2016
    Posts:
    723
    Thank you... the solution works perfect. Gladly your solution helped me finding the reason why it snaps back to 4.5. The Jetbrains Rider Unity Plugin also has a FixTargetVersion and guess what value it sets the target version :)

    Your solution still helped a lot!
     
  33. friuns3

    friuns3

    Joined:
    Oct 30, 2009
    Posts:
    307
    hi im using 2017.1.2f, im getting this error
     
  34. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    I see this occasionally pop up with JSON .NET with generic collections and often with List<single>. Did this error come from a build? I generally see it because of code stripping.
     
  35. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    I've seen the same errors in 2017.2 betas. They've definitely changed the way the C# compiler is called in latest Unity versions, so the current integration mechanism no longer works.

    I switched back to the old mechanism where we had to mess with Unity installation folder. Check the updated version: https://bitbucket.org/alexzzzz/unity-c-5.0-and-6.0-integration/overview

    Note: the current version of the plugin doesn't work on per project basis, it rather affects all the projects that target Net 4.6. Projects targeting Net 2.0 shouldn't be affected.
     
  36. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Added a fallback to the stock Mono compiler if CSharp70Support is not found in the project folder.
     
  37. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Fixed issues with Net 2.0 where the compilers complained about unknown -sdk:unity option.
     
  38. rtumelty

    rtumelty

    Joined:
    Dec 11, 2011
    Posts:
    12
    Hey Alex, trying to get this working in Unity 2017.3 on Mac (for an iOS and Android project) and am running into difficulties. After following the installation instructions on BitBucket, I'm getting the following exception in the editor:

    Any idea what I've done wrong? The path within the Unity app for the location of mcs.exe was slightly different - MonoBleedingEdge\lib\mono\4.5
     
  39. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    CSharpVNextSupport 4.0.2

    Some big changes:

    1. New integration mechanism. No need to modify files in Unity installation folder. UnityEditor.dll is patched on the fly in memory thanks to Harmony.

    2. Unity 2018.1.0b3 support.

    3. macOS support fixes.

    mac.png
    win.png
     
    5argon, Anvoker, MaxEden and 2 others like this.
  40. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555
    Thank you! I have been enjoying tuples and expression bodied get set so far.

    It would be a next big step if we somehow can convert portable PDB to MDB to allow macOS to see line numbers. In unit testing unfortunately the line number is quite critical. But in exchange for tuples I can put an exception string on each assert so I know where is the problematic assert for the time being.

    Microsoft.DiaSymReader.PortablePdb and Mono.Cecil.Mdb might be 2 things that can enable this conversion, but my understanding of metadata and debug symbols are zero and it is impossible for me to start hacking a solution.
     
    Last edited: Feb 2, 2018
  41. CodeLiftSleep

    CodeLiftSleep

    Joined:
    Jul 15, 2017
    Posts:
    44
    what happened to the version that worked with Unity 2017.1.0.f3? It's nowhere to be found and none of the other versions work right with the project I am using...I was using this in that project but didn't upload it to github and my harddrive crashed so I had to redownload the project from there...

    using the new version gives me the error:
    asyncOp.completed: async does not contain a method named completed and no other blah blah blah...are you missing an assembly file or reference?

    Tried re-importing and still the same...tried using 5.6 version and it gives me a whole host of other errors besides that one.

    UPDATE: hmm...I see it's supposed to be 3.23 after reading up the page some but I tried that one already and got the same error...
     
    Last edited: Feb 19, 2018
  42. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    2017.1 is a bit outdated. Import this unitypackage into the project. It contains a couple of fixes specifically for 2017.1.
     

    Attached Files:

  43. aranthel09

    aranthel09

    Joined:
    Jul 17, 2015
    Posts:
    66
    I'm getting this error when installing the package:


    Code (CSharp):
    1. Assets/CSharp vNext Support/AsyncTools/AsyncTools.cs(221,56): error CS1644: Feature `expression body constructor' cannot be used because it is not part of the C# 6.0 language specification
    Any idea why?

    EDIT: I installed an earlier version CSharp70Support 2.0.5.zip. It installed successfully without any errors, but now I get this:

    Code (CSharp):
    1. error CS1644: Feature `tuples' cannot be used because it is not part of the C# 6.0 language specification
    Shouldn't I be able to use Tuples by simply installing this package?
     
    Last edited: Feb 22, 2018
  44. starikcetin

    starikcetin

    Joined:
    Dec 7, 2017
    Posts:
    340
    Good job and thank you for making this open source.

    ---

    Edit:

    I get this error:
    Code (csharp):
    1. Assets\Testing.cs(2,24): error CS0234: The type or namespace name 'Tasks' does not exist in the namespace 'System.Threading' (are you missing an assembly reference?)
    For this line:
    Code (csharp):
    1. using System.Threading.Tasks;
    I'm pretty sure I followed all of your instruction on the BitBucket page correctly. I'm using 2017.3.1f1.
     
    Last edited: Mar 18, 2018
  45. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,550
    If you're using 2017.3, why are you trying to use that package? 2017.3 has C#6 support. Just turn it on ProjectSettings>Player>Other Settings>API Compatibility Level>NET 4.6
     
    starikcetin likes this.
  46. starikcetin

    starikcetin

    Joined:
    Dec 7, 2017
    Posts:
    340
    I guess you can tell I've been away from the latest news for a while.

    Thanks, I'll check that setting out.
     
    Invertex likes this.
  47. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Since Unity 2017.x supports NET 4.x and C# 6.0 out of the box, the latest versions of my Roslyn integration plugin are mostly targetted to add what is still missing - C# 7.x support.
     
    starikcetin likes this.
  48. MapMan

    MapMan

    Joined:
    Oct 27, 2013
    Posts:
    38
    Hey @alexzzzz ! First of all, thank you for the plugin and ongoing support :)

    I am in the process of updating Unity from 5.6 to 2018.1. I am not interested in using a roslyn compiler anymore as c# 7 features are not that important for me. I do want to be able to user TPL and async/await patterns.

    I used your plugin in the following ways:
    1. Run Tasks with the ThreadPool context, mainly via TaskEx.Run. For tasks in the ThreadPool, I used AsyncTools.ToUpdate awaiter to be able to interact with Unity APIs.
    2. Used UnityScheduler to enable task continuation - I now know this is no longer available.
    3. Implemented custom Awaiters for YieldInstruction and CustomYieldInstruction so I could await yield instructions such as WaitUntil
    4. Implemented TaskYieldInstruction so I could yield tasks in coroutines

    Do you have any idea how to accomplish the above functionalities with Unity 2018.1 but without your plugin? Or is your plugin (or parts of it, like AsyncTools) required to achieve the above?

    Do you also happen to know what's the relation of your plugin (or parts of it) to this project: https://github.com/svermeulen/Unity3dAsyncAwaitUtil ?

    So far, I did the following:
    1. Started by removing your plugin altogether
    2. Changed TaskEx to Task references
    3. Brought back AsyncTools.cs and refactored AsyncTools.ToUpdate to AsyncTools.ToMainThread. I assumed the awaiters you implemented should work regardless whether I use roslyn compiler or not.
    4. Removed UnityTaskScheduler parameters from Task.ContinueWith usage. Will this explode?
    5. My yield instruction awaiters didn't seem to need an update
    6. Replaced my TaskYieldInstructions with Task extensions from here https://github.com/svermeulen/Unity...ugins/AsyncAwaitUtil/Source/TaskExtensions.cs

    Alternatively, if it's not possible to achieve the aforementioned functionalities, will I be able to fulfill my requirements utilizing latest version of your plugin with roslyn compiler? Are you planning on supporting Unity 2018.1+ or are you depracating the plugin?

    I know not all of this is directly related to your plugin but possibly you could help me on some of the points and show me the right direction.
    Regardless, thank you for all the amazing work you did on this plugin. It made working with Unity much easier :)
     
    Last edited: May 15, 2018
  49. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555
    @MapMan In 2018.1 Unity introduced C# Jobs, if this is your own code I really recommend trying to learn and get your code into that system since it includes many performance boost to come from Unity's own compiler.

    But if you are going to use Task, just by changing .NET to 4.x in Player Settings it should already include C# 6.0... you can use Task, async, await, expression bodied, etc.

    Ps. not sure if related or not but I do have some code similar to what you are describing designed to work on task in a yield instruction.

    Code (CSharp):
    1. public static class TaskExtension
    2. {
    3.     public static IEnumerator YieldWait(this Task task)
    4.     {
    5.         while (task.IsCompleted == false)
    6.         {
    7.             yield return null;
    8.         }
    9.     }
    10.  
    11.     public const int timeOut = 25;
    12.  
    13.     /// <summary>
    14.     /// Make a Task yieldable, but there is a time out so it is suitable for running tests.
    15.     /// </summary>
    16.     public static IEnumerator YieldWaitTest(this Task task)
    17.     {
    18.         float timeTaken = 0;
    19.         while (task.IsCompleted == false)
    20.         {
    21.             if(task.IsCanceled)
    22.             {
    23.                 Assert.Fail("Task canceled!");
    24.             }
    25.             yield return null;
    26.             timeTaken += Time.deltaTime;
    27.             if(timeTaken > timeOut)
    28.             {
    29.                 Assert.Fail("Time out!");
    30.             }
    31.         }
    32.         Assert.That(task.IsFaulted,Is.Not.True,task.Exception?.ToString());
    33.         Debug.Log("Task time taken : " + timeTaken);
    34.     }
    35.  
    36.     public static async Task ShouldThrow<T>(this Task asyncMethod) where T : Exception
    37.     {
    38.         await ShouldThrow<T>(asyncMethod,"");
    39.     }
    40.  
    41.     public static async Task ShouldThrow<T>(this Task asyncMethod, string message) where T : Exception
    42.     {
    43.         try
    44.         {
    45.             await asyncMethod; //Should throw..
    46.         }
    47.         catch (T)
    48.         {
    49.             //Task should throw Aggregate but add this just in case.
    50.             Debug.Log("Caught an exception : " + typeof(T).FullName + " !!");
    51.             return;
    52.         }
    53.         catch (AggregateException ag)
    54.         {
    55.             foreach (Exception e in ag.InnerExceptions)
    56.             {
    57.                 Debug.Log("Caught an exception : " + e.GetType().FullName + " !!");
    58.                 if (message != "")
    59.                 {
    60.                     //Fails here if we find any other inner exceptions
    61.                     Assert.That(e, Is.TypeOf<T>(), message + " | " + e.ToString());
    62.                 }
    63.                 else
    64.                 {
    65.                     //Fails here also
    66.                     Assert.That(e, Is.TypeOf<T>(), e.ToString() + " " + "An exception should be of type " + typeof(T).FullName);
    67.                 }
    68.             }
    69.             return;
    70.         }
    71.         Assert.Fail("Expected an exception of type " + typeof(T).FullName + " but no exception was thrown."  );
    72.     }
    73.  
    74. }
     
    Last edited: May 15, 2018
    twobob likes this.
  50. malyzeli

    malyzeli

    Joined:
    May 1, 2014
    Posts:
    11
    Hello @alexzzzz, thanks for your awesome utility!

    I'm having a small issue in Jetbrains Rider with dynamic binding - editor reports the following error...

    One or more types required to compile a dynamic expression cannot be found. 
    Are you missing references to Microsoft.CSharp.dll and System.Core.dll?


    This is the code in question. Method call EntityCreated is marked as error. Also posted an screenshot below.

    Code (CSharp):
    1. public void NotifyEntityCreated(EntityId entityId) =>
    2.    EntityCreated((dynamic) entityId); /* this method call */
    3.  
    4. void EntityCreated(UnitId unitId) =>
    5.    unitRenderer.RegisterUnit(unitId);
    6. // void EntityCreated(ObjectId objectId) { }
    7. // void EntityCreated(EffectId effectId) { }
    8. // ...
    Application works as expected, Unity does not report any problem, game runs. This error is visible only in Rider. Unfortunately it is not possible to disable this error checking by adding disable instruction comment, so it is quite annoying and I would be happy if I could get rid of it!

    Interesting is that if I let Rider to add reference to CSharp.dll, then the error disappears until I save the file/project, after hitting save it is back...

    Looked into csproj file and import instruction is included there correctly I guess...

    <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />


    No idea why is this happening...

    Let me know if you need more info to look into this.

    Have a great day!

    Jiri
     

    Attached Files: