引擎版本获取

有些需求工程中需要检测引擎版本,如在支持多个引擎版本的插件,在引擎中包含不同的模块,引擎版本之间 API 的差异等。

C++ 获取引擎版本

Runtime/Launch/Resources/Version.h 中有版本宏定义:

Runtime/Launch/Resources/Version.h
1
2
3
4
// newer than a 4.11.* version, regardless of the changelist that it was built with)
#define ENGINE_MAJOR_VERSION 4
#define ENGINE_MINOR_VERSION 26
#define ENGINE_PATCH_VERSION 2

在代码中通过预处理指令即可使用。

从 TargetRules 获取引擎版本

TargetRules 中具有 Version(ReadOnlyBuildVersion)成员,它是 BuildVersion 的类型,定义在 Programs\UnrealBuildTool\System\BuildVersion.cs 中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// UnrealBuildTools/System/BuildVersion.cs
namespace UnrealBuildTool
{
/// <summary>
/// Holds information about the current engine version
/// </summary>
[Serializable]
public class BuildVersion
{
/// <summary>
/// The major engine version (4 for UE4)
/// </summary>
public int MajorVersion;

/// <summary>
/// The minor engine version
/// </summary>
public int MinorVersion;

/// <summary>
/// The hotfix/patch version
/// </summary>
public int PatchVersion;

/// <summary>
/// The changelist that the engine is being built from
/// </summary>
public int Changelist;

/// <summary>
/// The changelist that the engine maintains compatibility with
/// </summary>
public int CompatibleChangelist;

/// <summary>
/// Whether the changelist numbers are a licensee changelist
/// </summary>
public bool IsLicenseeVersion;

/// <summary>
/// Whether the current build is a promoted build, that is, built strictly from a clean sync of the given changelist
/// </summary>
public bool IsPromotedBuild;

/// <summary>
/// Name of the current branch, with '/' characters escaped as '+'
/// </summary>
public string BranchName;

/// <summary>
/// The current build id. This will be generated automatically whenever engine binaries change if not set in the default Engine/Build/Build.version.
/// </summary>
public string BuildId;

/// <summary>
/// The build version string
/// </summary>
public string BuildVersionString;

// ...
}
}

其中的 MajorVersion/MinorVersion/PatchVersion 分别对应 X.XX.X。

在 UE4.19 版本之前从 UBT 获取引擎版本比较麻烦:

1
2
3
4
5
6
7
BuildVersion Version;
if (BuildVersion.TryRead(BuildVersion.GetDefaultFileName(), out Version))
{
System.Console.WriteLine(Version.MajorVersion);
System.Console.WriteLine(Version.MinorVersion);
System.Console.WriteLine(Version.PatchVersion);
}

在 UE4.19 及以后的引擎版本,可以通过 ReadOnlyTargetRules.Version 来获得,它是 ReadOnlyBuildVersion 类型,包裹了一个 BuildVersion 类。

可以在 Target.cs 或者 Build.cs 里通过 Target.Version 来访问引擎版本,可以根据不同的引擎版本来使用不同的库。