Unity独立构建版本如何获取构建DateTime?有无内置实现方案?
获取Unity独立构建程序的构建DateTime的解决方案
嘿,我完全懂你想不用手动更新就能拿到独立构建程序发布日期的需求——确实Unity的Application类或者核心API里没有直接提供这个功能,但你找到的那个基于程序集版本的思路其实是可行的,只是原代码里有几个小问题导致没返回正确结果,我来帮你修正和补充更可靠的方案:
方法一:利用.NET程序集版本自动生成的时间信息
.NET程序集的Version字段里,Build和Revision默认是和构建时间绑定的:Build代表2000年1月1日以来的天数,Revision是当天的秒数除以2(这是旧版本.NET的遗留规则)。原代码的问题是计算逻辑有点绕,而且只返回了年份,我给你修正后的完整实现:
using System; using System.Reflection; using UnityEngine; public static class BuildDateTool { public static DateTime GetPlayerBuildDateTime() { // 获取游戏的入口程序集(仅在独立构建中有效,编辑器里会返回null) var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { Debug.LogWarning("当前在Unity编辑器中运行,无法获取构建时间"); return DateTime.MinValue; } var assemblyVersion = entryAssembly.GetName().Version; if (assemblyVersion == null) { Debug.LogWarning("程序集版本信息缺失"); return DateTime.MinValue; } // 计算构建时间:从2000-01-01开始累加天数和秒数 var buildDateTime = new DateTime(2000, 1, 1) .AddDays(assemblyVersion.Build) .AddSeconds(assemblyVersion.Revision * 2); Debug.Log($"当前构建的时间:{buildDateTime:yyyy-MM-dd HH:mm:ss}"); return buildDateTime; } }
注意事项
- 这个方法仅在打包后的独立程序中有效,编辑器里运行会返回
DateTime.MinValue,因为编辑器的入口程序集不是你的游戏程序集。 - 如果你的项目手动修改过程序集版本的生成规则(比如在
AssemblyInfo.cs里固定了Build和Revision),这个方法就会失效。
方法二:构建时自动写入时间到PlayerSettings(更可靠)
如果想要更稳定、甚至在编辑器里也能查看最新构建时间的方案,可以写一个编辑器脚本,监听构建开始事件,自动把当前时间写入PlayerSettings的自定义属性,运行时直接读取即可:
编辑器脚本(放在Editor文件夹下)
using UnityEditor; using UnityEngine; [InitializeOnLoad] public static class AutoRecordBuildDate { static AutoRecordBuildDate() { // 注册构建回调,在构建前执行我们的逻辑 BuildPlayerWindow.RegisterBuildPlayerHandler(BuildWithAutoDate); } private static void BuildWithAutoDate(BuildPlayerOptions buildOptions) { // 获取当前UTC时间(避免时区问题),格式化为易读字符串 string currentBuildDate = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss UTC"); // 写入到PlayerSettings的自定义属性中(Unity 2020及以上版本支持) PlayerSettings.SetCustomProperty("BuildDateTime", currentBuildDate); // 执行原本的构建流程 BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(buildOptions); } }
运行时读取代码
using UnityEngine; public static class BuildDateReader { public static string GetBuildDate() { // 读取自定义属性,没有的话返回默认值 return PlayerSettings.GetCustomProperty("BuildDateTime")?.ToString() ?? "未知构建时间"; } }
优势
- 完全不需要手动操作,每次构建都会自动更新时间。
- 时区可控(用UTC时间避免不同地区构建的时间差异)。
- 编辑器里也能通过
PlayerSettings.GetCustomProperty("BuildDateTime")查看最新的构建时间。 - 不受程序集版本设置的影响,稳定性更高。
内容的提问来源于stack exchange,提问作者Muhammad Faizan Khan
相关产品推荐
相关产品推荐

