unity設(shè)置.net framework 版本

Using .NET 4.x in Unity

設(shè)置的方法:

image.png

image.png

原貼地址Unity - Manual: .NET profile support (unity3d.com)

C# and .NET, the technologies underlying Unity scripting, have continued to receive updates since Microsoft originally released them in 2002. But Unity developers may not be aware of the steady stream of new features added to the C# language and .NET Framework. That's because before Unity 2017.1, Unity has been using a .NET 3.5 equivalent scripting runtime, missing years of updates.

With the release of Unity 2017.1, Unity introduced an experimental version of its scripting runtime upgraded to a .NET 4.6, C# 6 compatible version. In Unity 2018.1, the .NET 4.x equivalent runtime is no longer considered experimental, while the older .NET 3.5 equivalent runtime is now considered to be the legacy version. And with the release of Unity 2018.3, Unity is projecting to make the upgraded scripting runtime the default selection, and to update even further to C# 7. For more information and the latest updates on this roadmap, read Unity's blog post or visit their Experimental Scripting Previews forum. In the meantime, check out the sections below to learn more about the new features available now with the .NET 4.x scripting runtime.

Prerequisites

Enabling the .NET 4.x scripting runtime in Unity

To enable the .NET 4.x scripting runtime, take the following steps:

  1. Open PlayerSettings in the Unity Inspector by selecting Edit > Project Settings > Player.

  2. Under the Configuration heading, click the Scripting Runtime Version dropdown and select .NET 4.x Equivalent. You will be prompted to restart Unity.

Select .NET 4.x equivalent

Choosing between .NET 4.x and .NET Standard 2.0 profiles

Once you've switched to the .NET 4.x equivalent scripting runtime, you can specify the Api Compatibility Level using the dropdown menu in the PlayerSettings (Edit > Project Settings > Player). There are two options:

  • .NET Standard 2.0. This profile matches the .NET Standard 2.0 profile published by the .NET Foundation. Unity recommends .NET Standard 2.0 for new projects. It's smaller than .NET 4.x, which is advantageous for size-constrained platforms. Additionally, Unity has committed to supporting this profile across all platforms that Unity supports.

  • .NET 4.x. This profile provides access to the latest .NET 4 API. It includes all of the code available in the .NET Framework class libraries and supports .NET Standard 2.0 profiles as well. Use the .NET 4.x profile if your project requires part of the API not included in the .NET Standard 2.0 profile. However, some parts of this API may not be supported on all of Unity's platforms.

You can read more about these options in Unity's blog post.

Adding assembly references when using the .NET 4.x Api Compatibility Level

When using the .NET Standard 2.0 setting in the Api Compatibility Level dropdown, all assemblies in the API profile are referenced and usable. However, when using the larger .NET 4.x profile, some of the assemblies that Unity ships with aren't referenced by default. To use these APIs, you must manually add an assembly reference. You can view the assemblies Unity ships with in the MonoBleedingEdge/lib/mono directory of your Unity editor installation:

MonoBleedingEdge directory

For example, if you're using the .NET 4.x profile and want to use HttpClient, you must add an assembly reference for System.Net.Http.dll. Without it, the compiler will complain that you're missing an assembly reference:

missing assembly reference

Visual Studio regenerates .csproj and .sln files for Unity projects each time they're opened. As a result, you cannot add assembly references directly in Visual Studio because they'll be lost upon reopening the project. Instead, a special text file named csc.rsp must be used:

  1. Create a new text file named csc.rsp in your Unity project's root Assets directory.

  2. On the first line in the empty text file, enter: -r:System.Net.Http.dll and then save the file. You can replace "System.Net.Http.dll" with any included assembly that might be missing a reference.

  3. Restart the Unity editor.

Taking advantage of .NET compatibility

In addition to new C# syntax and language features, the .NET 4.x scripting runtime gives Unity users access to a huge library of .NET packages that are incompatible with the legacy .NET 3.5 scripting runtime.

Add packages from NuGet to a Unity project

NuGet is the package manager for .NET. NuGet is integrated into Visual Studio. However, Unity projects require a special process to add NuGet packages. This is because when you open a project in Unity, its Visual Studio project files are regenerated, undoing necessary configurations. To add a package from NuGet to your Unity project do the following:

  1. Browse NuGet to locate a compatible package you'd like to add (.NET Standard 2.0 or .NET 4.x). This example will demonstrate adding Json.NET, a popular package for working with JSON, to a .NET Standard 2.0 project.

  2. Click the Download button:

    download button
  3. Locate the downloaded file and change the extension from .nupkg to .zip.

  4. Within the zip file, navigate to the lib/netstandard2.0 directory and copy the Newtonsoft.Json.dll file.

  5. In your Unity project's root Assets folder, create a new folder named Plugins. Plugins is a special folder name in Unity. See the Unity documentation for more information.

  6. Paste the Newtonsoft.Json.dll file into your Unity project's Plugins directory.

  7. Create a file named link.xml in your Unity project's Assets directory and add the following XML. This will ensure Unity's bytecode stripping process does not remove necessary data when exporting to an IL2CPP platform. While this step is specific to this library, you may run into problems with other libraries that use Reflection in similar ways. For more information, please see Unity's docs on this topic.

    XMLCopy

    <linker>
      <assembly fullname="System.Core">
        <type fullname="System.Linq.Expressions.Interpreter.LightLambda" preserve="all" />
      </assembly>
    </linker>
    
    

With everything in place, you can now use the Json.NET package.

C#Copy

using Newtonsoft.Json;
using UnityEngine;

public class JSONTest : MonoBehaviour
{
    class Enemy
    {
        public string Name { get; set; }
        public int AttackDamage { get; set; }
        public int MaxHealth { get; set; }
    }
    private void Start()
    {
        string json = @"{
            'Name': 'Ninja',
            'AttackDamage': '40'
            }";

        var enemy = JsonConvert.DeserializeObject<Enemy>(json);

        Debug.Log($"{enemy.Name} deals {enemy.AttackDamage} damage.");
        // Output:
        // Ninja deals 40 damage.
    }
}

This is a simple example of using a library which has no dependencies. When NuGet packages rely on other NuGet packages, you would need to download these dependencies manually and add them to the project in the same way.

New syntax and language features

Using the updated scripting runtime gives Unity developers access to C# 6 and a host of new language features and syntax.

Auto-property initializers

In Unity's .NET 3.5 scripting runtime, the auto-property syntax makes it easy to quickly define uninitialized properties, but initialization has to happen elsewhere in your script. Now with the .NET 4.x runtime, it's possible to initialize auto-properties in the same line:

C#Copy

// .NET 3.5
public int Health { get; set; } // Health has to be initialized somewhere else, like Start()

// .NET 4.x
public int Health { get; set; } = 100;

String interpolation

With the older .NET 3.5 runtime, string concatenation required awkward syntax. Now with the .NET 4.x runtime, the $ string interpolation feature allows expressions to be inserted into strings in a more direct and readable syntax:

C#Copy

// .NET 3.5
Debug.Log(String.Format("Player health: {0}", Health)); // or
Debug.Log("Player health: " + Health);

// .NET 4.x
Debug.Log($"Player health: {Health}");

Expression-bodied members

With the newer C# syntax available in the .NET 4.x runtime, lambda expressions can replace the body of functions to make them more succinct:

C#Copy

// .NET 3.5
private int TakeDamage(int amount)
{
    return Health -= amount;
}

// .NET 4.x
private int TakeDamage(int amount) => Health -= amount;

You can also use expression-bodied members in read-only properties:

C#Copy

// .NET 4.x
public string PlayerHealthUiText => $"Player health: {Health}";

Task-based Asynchronous Pattern (TAP)

Asynchronous programming allows time consuming operations to take place without causing your application to become unresponsive. This functionality also allows your code to wait for time consuming operations to finish before continuing with code that depends on the results of these operations. For example, you could wait for a file to load or a network operation to complete.

In Unity, asynchronous programming is typically accomplished with coroutines. However, since C# 5, the preferred method of asynchronous programming in .NET development has been the Task-based Asynchronous Pattern (TAP) using the async and await keywords with System.Threading.Task. In summary, in an async function you can await a task's completion without blocking the rest of your application from updating:

C#Copy

// Unity coroutine
using UnityEngine;
public class UnityCoroutineExample : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine(WaitOneSecond());
        DoMoreStuff(); // This executes without waiting for WaitOneSecond
    }
    private IEnumerator WaitOneSecond()
    {
        yield return new WaitForSeconds(1.0f);
        Debug.Log("Finished waiting.");
    }
}

C#Copy

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
    private async void Start()
    {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
    }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

TAP is a complex subject, with Unity-specific nuances developers should consider. As a result, TAP isn't a universal replacement for coroutines in Unity; however, it is another tool to leverage. The scope of this feature is beyond this article, but some general best practices and tips are provided below.

Getting started reference for TAP with Unity

These tips can help you get started with TAP in Unity:

  • Asynchronous functions intended to be awaited should have the return type Task or Task<TResult>.
  • Asynchronous functions that return a task should have the suffix "Async" appended to their names. The "Async" suffix helps indicate that a function should always be awaited.
  • Only use the async void return type for functions that fire off async functions from traditional synchronous code. Such functions cannot themselves be awaited and shouldn't have the "Async" suffix in their names.
  • Unity uses the UnitySynchronizationContext to ensure async functions run on the main thread by default. The Unity API isn't accessible outside of the main thread.
  • It's possible to run tasks on background threads with methods like Task.Run and Task.ConfigureAwait(false). This technique is useful for offloading expensive operations from the main thread to enhance performance. However, using background threads can lead to problems that are difficult to debug, such as race conditions.
  • The Unity API isn't accessible outside the main thread.
  • Tasks that use threads aren't supported on Unity WebGL builds.

Differences between coroutines and TAP

There are some important differences between coroutines and TAP / async-await:

  • Coroutines cannot return values, but Task<TResult> can.
  • You cannot put a yield in a try-catch statement, making error handling difficult with coroutines. However, try-catch works with TAP.
  • Unity's coroutine feature isn't available in classes that don't derive from MonoBehaviour. TAP is great for asynchronous programming in such classes.
  • At this point, Unity doesn't suggest TAP as a wholesale replacement of coroutines. Profiling is the only way to know the specific results of one approach versus the other for any given project.

Note

As of Unity 2018.2, debugging async methods with break points isn't fully supported; however, this functionality is expected in Unity 2018.3.

nameof operator

The nameof operator gets the string name of a variable, type, or member. Some cases where nameof comes in handy are logging errors, and getting the string name of an enum:

C#Copy

// Get the string name of an enum:
enum Difficulty {Easy, Medium, Hard};
private void Start()
{
    Debug.Log(nameof(Difficulty.Easy));
    RecordHighScore("John");
    // Output:
    // Easy
    // playerName
}
// Validate parameter:
private void RecordHighScore(string playerName)
{
    Debug.Log(nameof(playerName));
    if (playerName == null) throw new ArgumentNullException(nameof(playerName));
}

Caller info attributes

Caller info attributes provide information about the caller of a method. You must provide a default value for each parameter you want to use with a Caller Info attribute:

C#Copy

private void Start ()
{
    ShowCallerInfo("Something happened.");
}
public void ShowCallerInfo(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    Debug.Log($"message: {message}");
    Debug.Log($"member name: {memberName}");
    Debug.Log($"source file path: {sourceFilePath}");
    Debug.Log($"source line number: {sourceLineNumber}");
}
// Output:
// Something happened
// member name: Start
// source file path: D:\Documents\unity-scripting-upgrade\Unity Project\Assets\CallerInfoTest.cs
// source line number: 10

Using static

Using static allows you to use static functions without typing its class name. With using static, you can save space and time if you need to use several static functions from the same class:

C#Copy

// .NET 3.5
using UnityEngine;
public class Example : MonoBehaviour
{
    private void Start ()
    {
        Debug.Log(Mathf.RoundToInt(Mathf.PI));
        // Output:
        // 3
    }
}

C#Copy

// .NET 4.x
using UnityEngine;
using static UnityEngine.Mathf;
public class UsingStaticExample: MonoBehaviour
{
    private void Start ()
    {
        Debug.Log(RoundToInt(PI));
        // Output:
        // 3
    }
}

IL2CPP Considerations

When exporting your game to platforms like iOS, Unity will use its IL2CPP engine to "transpile" IL to C++ code which is then compiled using the native compiler of the target platform. In this scenario, there are several .NET features which are not supported, such as parts of Reflection, and usage of the dynamic keyword. While you can control using these features in your own code, you may run into problems using 3rd party DLLs and SDKs which were not written with Unity and IL2CPP in mind. For more information on this topic, please see the Scripting Restrictions docs on Unity's site.

Additionally, as mentioned in the Json.NET example above, Unity will attempt to strip out unused code during the IL2CPP export process. While this typically isn't an issue, with libraries that use Reflection, it can accidentally strip out properties or methods that will be called at run time that can't be determined at export time. To fix these issues, add a link.xml file to your project which contains a list of assemblies and namespaces to not run the stripping process against. For full details, please see Unity's docs on bytecode stripping.

.NET 4.x Sample Unity Project

The sample contains examples of several .NET 4.x features. You can download the project or view the source code on GitHub.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖晌梨,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡博秫,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)眶掌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)挡育,“玉大人,你說(shuō)我怎么就攤上這事朴爬〖春” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)母赵。 經(jīng)常有香客問(wèn)我逸爵,道長(zhǎng),這世上最難降的妖魔是什么凹嘲? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任师倔,我火速辦了婚禮,結(jié)果婚禮上周蹭,老公的妹妹穿的比我還像新娘趋艘。我一直安慰自己,他們只是感情好凶朗,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布瓷胧。 她就那樣靜靜地躺著,像睡著了一般棚愤。 火紅的嫁衣襯著肌膚如雪搓萧。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,370評(píng)論 1 302
  • 那天遇八,我揣著相機(jī)與錄音矛绘,去河邊找鬼。 笑死刃永,一個(gè)胖子當(dāng)著我的面吹牛货矮,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播斯够,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼囚玫,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了读规?” 一聲冷哼從身側(cè)響起抓督,我...
    開(kāi)封第一講書(shū)人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎束亏,沒(méi)想到半個(gè)月后铃在,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡碍遍,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年定铜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片怕敬。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡揣炕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出东跪,到底是詐尸還是另有隱情畸陡,我是刑警寧澤鹰溜,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站丁恭,受9級(jí)特大地震影響曹动,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜涩惑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一仁期、第九天 我趴在偏房一處隱蔽的房頂上張望桑驱。 院中可真熱鬧竭恬,春花似錦、人聲如沸熬的。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)押框。三九已至岔绸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間橡伞,已是汗流浹背盒揉。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留兑徘,地道東北人刚盈。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像挂脑,于是被迫代替她去往敵國(guó)和親藕漱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 歷史 在Unity 2017.1之前崭闲,Unity使用的是一個(gè)相當(dāng)于.NET 3.5的runtime肋联,多年未更新。 ...
    勤奮happyfire閱讀 2,128評(píng)論 0 1
  • Coroutine(協(xié)程)我想大家都很熟悉了刁俭,由于Unity是單線程的引擎橄仍,我們?cè)谧鲆恍┊惒讲僮鞯臅r(shí)候都是靠著協(xié)程...
    上善若水_2019閱讀 3,133評(píng)論 2 1
  • awesome-dotnet-core .NET Core框架侮繁、庫(kù)和軟件的中文收錄大全。內(nèi)容包括:庫(kù)翘魄、工具鼎天、框架、...
    NicoSaron閱讀 757評(píng)論 0 4
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險(xiǎn)厭惡者暑竟,不喜歡去冒險(xiǎn)斋射,但是人生放棄了冒險(xiǎn)育勺,也就放棄了無(wú)數(shù)的可能。 ...
    yichen大刀閱讀 6,049評(píng)論 0 4
  • 公元:2019年11月28日19時(shí)42分農(nóng)歷:二零一九年 十一月 初三日 戌時(shí)干支:己亥乙亥己巳甲戌當(dāng)月節(jié)氣:立冬...
    石放閱讀 6,879評(píng)論 0 2