将 Unity 的默认编辑器改为 VSCode

为什么要更改

有两个原因

第一,Visual Studio 默认使用 GBK 编码,写的中文文字在 Unity 预览界面显示是乱码的

第二,我正在学习王国之梦,看到老师的 VSCode 使用 Code GeeX 这个 AI 可以快速生成代码,非常羡慕。但是我不知道 Visual Studio 如何快速生成代码,听说 copilot 可以,但是需要 10 美元一个月,我太穷了,买不起。所以还是跟着老师用 VSCode + Code GeeX 算了

怎么更改

主要参考视频:为Unity开发环境设置VSCode,这是我从油管搬运的视频

视频绝大部分操作都是正确的,有以下三点需要补充或纠正

需要手动安装 dotnet

自动安装 dotnet 这块在中国国内不行,会被墙,需要手动安装和配置

visual studio code 手动配置 VSCode 环境,参考:【Unity 踩坑系列】配置VScode环境Downloading the.NET Runtime Failed to download.NET 7.0.9installation timed out,博客中 settings.json 可能也不太全,我这边放上最全的配置

内容为

    "dotnetAcquisitionExtension.existingDotnetPath": [
        {"extensionId": "ms-dotnettools.csdevkit", "path": "D:\\hellozjf\\soft\\dotnet-sdk-7.0.406-win-x64\\dotnet.exe"},
        {"extensionId": "ms-dotnettools.csharp", "path": "D:\\hellozjf\\soft\\dotnet-sdk-7.0.406-win-x64\\dotnet.exe"},
        {"extensionId": "visualstudiotoolsforunity.vstuc", "path": "D:\\hellozjf\\soft\\dotnet-sdk-7.0.406-win-x64\\dotnet.exe"}
    ],

dotnet SDK 的下载路径是https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-7.0.406-windows-x64-binaries,我下载后把它解压到了D:\\hellozjf\\soft\\dotnet-sdk-7.0.406-win-x64,然后配置了环境变量

注意,dotnet SDK 还有一个小坑,如果存在C:\Program Files\dotnet这个文件夹,visual studio code 就会优先从这个文件夹读取 dotnet 导致报错,最好把C:\Program Files\dotnet删掉。参考链接 How to fix "No .NET SDKs were found." error--VSCode

无需安装 Visual Studio Code

我使用的是 Unity 2023.3.0b8 版本,它的 Unity Registry 里面已经搜索不到 Visual Studio Code Editor 了

根据 Unity Development with VS Code 这篇文章的说法,只需要 Visual Studio Editor 版本在2.0.20或更高就行了,Visual Studio Code Editor包已经不维护了

安装 CodeGeeX

访问 codegeex 官网,然后下载 Visual Studio Code 插件,然后注册一个 codegeex 的账号,把 CodeGeeX 安装到 Visual Studio Code 之后,再登录账号就能使用 codegeex 使用 AI 自动提示代码了,非常方便

最终安装的插件

补充一下

我用的VSCode及其插件版本如下

Visual Studio Code 1.87.2
.NET Install Tool v2.0.2
C# v2.22.3
C# Dev Kit v1.4.29
IntelliCode for C# Dev Kit v0.1.26
Unity v1.0.0
Unity Code Snippets v2.4.0

dotnet-sdk 版本为 7.0.406-win-x64。我试过 dotnet-sdk-8.0.202-win-x64 无法进行调试

unity 版本为 2023.3.0b10。其它版本没试过,反正不要用团结引擎,我试过 1.0.4 版本,VSCode 无法调试,甚至连代码跳转都做不到,Visual Studio 2022 也无法调试

2024年4月21日补充

我在做麦田物语的时候,发现又报错了,然后我把 dotnet-sdk 版本改为 8.0.202 之后就是正常了,特别奇怪。之前应该是偷懒没好好验证,这里补充一下

我现在的 settings.json 文件内容如下

{
    "workbench.colorTheme": "Default Dark+",
    "git.autofetch": true,
    "git.enableSmartCommit": true,
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "[vue]": {
        "editor.defaultFormatter": "Vue.volar"
    },
    "http.proxyAuthorization": null,
    "gitlens.proxy": {},
    "editor.codeActionsOnSave": {
        
    },
    "dotnetAcquisitionExtension.existingDotnetPath": [


        {
            "extensionId": "ms-dotnettools.csdevkit",
            "path": "D:\\hellozjf\\soft\\dotnet-sdk-8.0.202-win-x64\\dotnet.exe"
        },
        {
            "extensionId": "ms-dotnettools.csharp",
            "path": "D:\\hellozjf\\soft\\dotnet-sdk-8.0.202-win-x64\\dotnet.exe"
        },
        {
            "extensionId": "visualstudiotoolsforunity.vstuc",
            "path": "D:\\hellozjf\\soft\\dotnet-sdk-8.0.202-win-x64\\dotnet.exe"
        }
    ],
    "Codegeex.Privacy": true,
    "browser": "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
    "dotnet.unitTestDebuggingOptions": {

    }
}

环境变量如下。注意,DOTNET_ROOT是vscode运行c#控制台程序所必须的环境变量,必须加上。我没加导致我花了几个小时在找原因。另外需要留意一下,系统变量优先级高于用户变量优先级,如果设置用户变量不生效,可以看看是不是系统变量被覆盖了

2024年4月24日补充

Visual Studio 也是可以将文件编码默认改成 UTF-8 的,见下图

但是这种方法只能对从 Visual Studio 创建的文件才有效,所以并不实用。

我写了一个 Java 代码,用于将 C# 文件编码从 GB2312 转换为 UTF-8

package cn.hellozjf.project.leetcode;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.*;
import java.time.temporal.ChronoUnit;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.TimeZone;

@Slf4j
@SpringBootApplication
public class LeetcodeApplication {

    public static void main(String[] args) {
        SpringApplication.run(LeetcodeApplication.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner() {
        return args -> {
//            DateTime begin = DateTime.of(0L);
//            log.info("begin = {}", begin.toString(TimeZone.getTimeZone("0")));
//            DateTime end = DateTime.now();
//            long betweenSeconds = LocalDateTimeUtil.between(begin.toLocalDateTime(), end.toLocalDateTime(), ChronoUnit.SECONDS);
//            log.info("betweenSeconds = {}", betweenSeconds);
//            DateTime vir = begin.offset(DateField.MINUTE, (int) betweenSeconds);
//            log.info("vir = {}", vir.toString(TimeZone.getTimeZone("0")));


            // 文件路径
            String filePath = "D:\\hellozjf\\code\\gitee\\MStudio\\FarmTutorial\\Assets\\Scripts";
            Queue<File> queue = new LinkedList<>();
            queue.offer(new File(filePath));
            while (!queue.isEmpty()) {
                File folder = queue.poll();
                final File[] files = folder.listFiles();
                for (File file : files) {
                    if (file.isDirectory()) {
                        queue.offer(file);
                    } else {
                        String fileName = file.getAbsolutePath();
                        if (isCsFile(fileName) && isGb2312(fileName)) {
                            convert(fileName, "GB2312", "UTF-8");
                        }
                    }
                }
            }
        };
    }

    private boolean isCsFile(String filePath) {
        int index = filePath.lastIndexOf('.');
        String extension = filePath.substring(index + 1);
        return "cs".equals(extension);
    }

    private void convert(String filePath, String sourceEncoding, String targetEncoding) throws Exception {

        String sourceFilePath = filePath + ".bak";
        String targetFilePath = filePath;
        File file = new File(filePath);
        file.renameTo(new File(sourceFilePath));
        try {
            // 读取原文件
            FileInputStream fis = new FileInputStream(sourceFilePath);
            InputStreamReader isr = new InputStreamReader(fis, sourceEncoding);
            BufferedReader reader = new BufferedReader(isr);

            // 写入新文件
            FileOutputStream fos = new FileOutputStream(targetFilePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, targetEncoding);
            BufferedWriter writer = new BufferedWriter(osw);

            // 逐行读取并写入
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }

            // 关闭流
            reader.close();
            writer.close();

            File oldFile = new File(sourceFilePath);
            oldFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isGb2312(String filePath) throws Exception {

        // 创建 UniversalDetector 对象
        UniversalDetector detector = new UniversalDetector(null);
        String encoding = null;

        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buf = new byte[4096];
            int nread;
            while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }
            detector.dataEnd();

            // 获取文件编码
            encoding = detector.getDetectedCharset();
            if (encoding != null) {
                System.out.println("Detected encoding: " + encoding);
            } else {
                System.out.println("No encoding detected.");
            }
        } finally {
            // 关闭detector
            detector.reset();
        }

        return "WINDOWS-1252".equals(encoding) || "GB18030".equals(encoding);
    }
}

参考链接

为Unity开发环境设置VSCode

【Unity 踩坑系列】配置VScode环境Downloading the.NET Runtime Failed to download.NET 7.0.9installation timed out

How to fix "No .NET SDKs were found." error--VSCode

Unity Development with VS Code

教程:使用 Visual Studio Code 调试 .NET 控制台应用程序

posted @   hellozjf  阅读(1577)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示