如何在 Unity3D 项目上启用 c# 7 功能 [英] How to enable c# 7 features on Unity3D projects

查看:82
本文介绍了如何在 Unity3D 项目上启用 c# 7 功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Unity3D 项目中编写了一个新方法(使用 Visual Studio 2017),对于该方法,我需要 C# 7 或更高版本.所以我按照

<小时>

对于 Unity3D <2018.3.*

我会告诉你我是如何在 Unity3D 项目中启用 C# 7.3 的(虽然它的一些功能还不能编译).但要注意:这种方法是一种黑客!这是 C# 7 在 Unity 中的过早和实验性用法.

如果您按照以下说明进行操作,我相信您可以轻松找到问题所在,因为就您的问题而言,很难为 SO 社区提供完整的 MCVE.但我相信你真正想要实现的是为 Unity 启用 C# 7,而不是解决项目属性窗口中的奇怪错误.

在继续之前,我建议您完全重新安装 Visual Studio 2017 和 Unity3D,以确保您没有任何与错误安装相关的问题.始终直接从 Unity 的网页下载 Unity,而不是使用 Viual Studio 的安装程序,这样您就可以获得最新版本.

在 Unity 3D 项目中启用 C# 7(在 Unity3D v.2018.2.10f、VS 2017 v.15.8.5 上测试)

  1. 首先创建一个新的空项目.

  2. 转到<代码>编辑 ->项目设置 ->Player,找到Other Settings 部分,然后在Configuration/Scripting Runtime Version 下选择.NET 4.x Equivalent.

  3. 我们想让 mcs.exe 使用 C# 7 的新实验性"功能处理 C# 代码.为此,只需在 Assets 文件夹中创建文件 mcs.rsp.编辑它并在其中写下这一行:

    -langversion:experimental

  4. 现在,在您的 Assets 文件夹中创建一个名为 Editor 的新文件夹.添加到此文件夹中的任何脚本都会使 Unity 创建一个 *.Editor.csproj 项目文件,其中包含旨在修改 Unity 编辑器的脚本.

  5. 我们需要告诉 Visual Studio 您的项目支持 C# 7.3 语言.这并不意味着 Unity 将能够编译 C# 7.3 的所有功能,但至少 Visual Studio 不会抱怨您尝试通过实验使用的功能.

    但是,如果您直接编辑 csproj 文件,Unity 会在某个时候自动覆盖它(Unity 总是自动生成项目和解决方案文件).所以你可以做的是安装一个钩子,在自动生成项目文件时调用它,这样你就可以自己打开项目文件并向它添加你的自定义(你的自定义不仅限于更改语言版本:你可以做更多的事情,但你必须明白你在这里做什么).

    为此,将以下脚本放在 Editor 文件夹中:

    #if ENABLE_VSTU使用 SyntaxTree.VisualStudio.Unity.Bridge;使用系统;使用 System.IO;使用 System.Linq;使用 System.Text;使用 System.Xml.Linq;使用 UnityEditor;使用 UnityEngine;[初始化加载]公共类 ProjectFilesGeneration{私有类 Utf8StringWriter : StringWriter{公共覆盖编码编码{得到 { 返回 Encoding.UTF8;}}}静态 ProjectFilesGeneration(){ProjectFilesGenerator.ProjectFileGeneration +=(字符串名称,字符串内容)=>{//在此处忽略您不想编辑的项目:if (name.EndsWith("Editor.csproj", StringComparison.InvariantCultureIgnoreCase)) 返回内容;Debug.Log($"自定义项目文件:'{name}'");//加载 csproj 文件:XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");XDocument xml = XDocument.Parse(content);//查找具有定义配置和平台的条件的所有属性组:XElement[] 节点 = xml.Descendants().哪里(孩子=>child.Name.LocalName == "PropertyGroup"&&(child.Attributes().FirstOrDefault(attr => attr.Name.LocalName == "Condition")?.Value.Contains("'$(Configuration)|$(Platform)'") ?? false)).ToArray();//添加<LangVersion>7.3</LangVersion>到这些 PropertyGroup:foreach(节点中的XElement节点)node.Add(new XElement(ns + "LangVersion", "7.3"));//写入csproj文件:使用 (Utf8StringWriter str = new Utf8StringWriter()){xml.Save(str);返回 str.ToString();}};}}#万一

如果您想完全了解项目文件中的更改,只需使用任何差异工具,将 csproj 文件的先前版本和新版本进行比较.上面的 hack 基本上与您在更改语言版本时发布的链接类似,只是每次 Unity 自动生成项目文件时都会这样做.Microsoft 还提供了大量关于 csproj 文件中定义的文档.

I wrote a new method in my Unity3D project (using Visual Studio 2017), and for that method I need C# 7 or greater. So I followed the instructions in this guide.

Now, when I try to open the project's properties, Visual Studio opens it, but then it suddenly closes right after opening. Now I can't even open project's properties.

This is how it looks:

Why am I getting the first and third errors? (the ones I showed in the gif)

解决方案

EDIT

The Roslyn compiler is now supported in Unity 2018.3, which allows you to use the latest C# 7 features!

See: https://blogs.unity3d.com/2018/09/13/unity-2018-3-beta-get-early-access-now/


For Unity3D < 2018.3.*

I will tell you how I have enabled C# 7.3 in Unity3D projects (although some of its features can't be compiled yet). But beware: this method is a hack! It is a premature and experimental usage of C# 7 in Unity.

If you follow the instructions below, I believe you may be able to easily track down the issue, given that in the case of your question it is quite difficult to provide a full MCVE for the SO community. But I believe that what you actually are trying to achieve is enabling C# 7 for Unity, and not solve the bizarre bug in the project properties window.

Before proceeding, I would recommend completely reinstalling Visual Studio 2017 and Unity3D, just to make sure that you are not having any issue related to a bad installation. Always download Unity directly from Unity's webpage instead of using Viual Studio's Installer, so you can get the latest version available.

Enabling C# 7 in Unity 3D projects (tested on Unity3D v.2018.2.10f, VS 2017 v.15.8.5)

  1. First create a new fresh empty project.

  2. Go to Edit -> Project Settings -> Player, find the Other Settings section, then under Configuration / Scripting Runtime Version choose .NET 4.x Equivalent.

  3. We want to tell mcs.exe to process the C# code using the new "experimental" features of C# 7. For that, just create the file mcs.rsp inside your Assets folder. Edit it and write the this line inside it:

    -langversion:experimental
    

  4. Now, create a new folder named Editor inside your Assets folder. Any scripts added to this folder will make Unity create a *.Editor.csproj project file, which holds contain scripts aimed to modify the Unity Editor.

  5. We need to tell Visual Studio that your project supports the C# 7.3 language. This doesn't mean that Unity will be able to compile all features of C# 7.3, but at least Visual Studio will not bitch about the features you are trying to use experimentally.

    However if you edit a csproj file directly, Unity will automatically overwrite it at some point (Unity always auto-generate project and solution files). So what you can do is to install a hook which is called when the project file is auto-generated, so you can open the project file yourself and add your customization to it (your customizations are not limited just to changing the language version: you could do more stuff, but you must understand what you are doing here).

    For this purpose, place the following script inside the Editor folder:

    #if ENABLE_VSTU
    
    using SyntaxTree.VisualStudio.Unity.Bridge;
    using System;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;
    using UnityEditor;
    using UnityEngine;
    
    [InitializeOnLoad]
    public class ProjectFilesGeneration
    {
        private class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }
        }
    
        static ProjectFilesGeneration()
        {
            ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
            {
                // Ignore projects you do not want to edit here:
                if (name.EndsWith("Editor.csproj", StringComparison.InvariantCultureIgnoreCase)) return content;
    
                Debug.Log($"CUSTOMIZING PROJECT FILE: '{name}'");
    
                // Load csproj file:
                XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
                XDocument xml = XDocument.Parse(content);
    
                // Find all PropertyGroups with Condition defining a Configuration and a Platform:
                XElement[] nodes = xml.Descendants()
                    .Where(child =>
                        child.Name.LocalName == "PropertyGroup"
                        && (child.Attributes().FirstOrDefault(attr => attr.Name.LocalName == "Condition")?.Value.Contains("'$(Configuration)|$(Platform)'") ?? false)
                    )
                    .ToArray();
    
                // Add <LangVersion>7.3</LangVersion> to these PropertyGroups:
                foreach (XElement node in nodes)
                    node.Add(new XElement(ns + "LangVersion", "7.3"));
    
                // Write to the csproj file:
                using (Utf8StringWriter str = new Utf8StringWriter())
                {
                    xml.Save(str);
                    return str.ToString();
                }
            };
        }
    }
    
    #endif
    

If you want to fully understand what has changed in your project file, just use any diff tool, to compare the previous version and the new version of the csproj file. The hack above basically does something similar to the link you've posted when changing the language version, except that it does that every time Unity auto-generates the project file. Microsoft also provides plenty of documentation on the definitions inside csproj files.

这篇关于如何在 Unity3D 项目上启用 c# 7 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆