You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Unity 2023中添加Nullable上下文?解决配置被覆盖问题

在Unity 2023中全局启用Nullable可空引用上下文的解决方案

方案一:使用Directory.Build.props(推荐,Unity 2021+支持)

Unity 2021及以上版本支持通过MSBuild的Directory.Build.props文件注入全局编译设置,不会被自动生成的csproj覆盖:

  1. 在Unity项目根目录创建名为Directory.Build.props的文件
  2. 将以下内容写入文件:
<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>
  1. 重启Unity,或者在Unity菜单中选择Assets > Open C# Project触发项目文件重新生成,此时所有自动生成的csproj都会继承全局Nullable启用的设置。

方案二:通过Editor脚本设置编译器参数

如果方案一不生效,可通过Editor脚本自动给项目添加编译器参数,确保每次生成csproj时都包含该设置:

  1. 在项目中创建Editor文件夹(如果没有的话)
  2. 在该文件夹下创建C#脚本,比如NullableSetup.cs,内容如下:
using UnityEditor;

[InitializeOnLoad]
public static class NullableSetup
{
    static NullableSetup()
    {
        // 给常用平台添加参数,可根据需求扩展其他平台
        UpdateCompilerArgs(BuildTargetGroup.Standalone);
        UpdateCompilerArgs(BuildTargetGroup.iOS);
        UpdateCompilerArgs(BuildTargetGroup.Android);
    }

    private static void UpdateCompilerArgs(BuildTargetGroup group)
    {
        var args = PlayerSettings.GetAdditionalCompilerArguments(group);
        if (!args.Contains("-nullable:enable"))
        {
            args += " -nullable:enable";
            PlayerSettings.SetAdditionalCompilerArguments(group, args);
        }
    }
}
  1. 保存脚本后,Unity会自动执行该代码,将-nullable:enable添加到指定平台的编译器参数中,后续生成的csproj会包含该设置。

为什么csc.rsp没生效?

在MacOS的Unity 2023环境中,csc.rsp的优先级可能被MSBuild的项目设置覆盖,或者Unity对csc.rsp的路径识别存在差异,导致参数未被正确应用。上述两个方案都是Unity官方支持的全局设置方式,稳定性更高。

内容的提问来源于stack exchange,提问作者Bharel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:38:26