在运行时访问Unity包版本



我正在开发一个自定义分析系统(这是一个自定义包(,当我查看数据时,知道这个包的哪个版本集成在unity应用程序中会非常有帮助。

有什么快速的解决方案可以在运行时检索pacakge版本吗?

如前所述,您可以使用ScriptableObject来存储稍后运行时的版本。

你可以像一样做

// See https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
#if UNITY_EDITOR
using UnityEditor;
#endif;
public class PackageVersion : ScriptableObject
{
// See https://docs.unity3d.com/ScriptReference/HideInInspector.html
[HideInInspector] public string Version;
#if UNITY_EDITOR
// Called automatically after open Unity and each recompilation
// See https://docs.unity3d.com/ScriptReference/InitializeOnLoadMethodAttribute.html
[InitializeOnLoadMethod]
private static void Init()
{
// See https://docs.unity3d.com/ScriptReference/Compilation.CompilationPipeline-compilationFinished.html
// Removing the callback before adding it makes sure it is only added once at a time
CompilationPipeline.compilationFinished -= OnCompilationFinished;
CompilationPipeline.compilationFinished += OnCompilationFinished;
}
private static void OnCompilationFinished()
{
// First get the path of the Package
// This is quite easy since this script itself belongs to your package's assemblies
var assembly = typeof(PackageVersion).Assembly;
// See https://docs.unity3d.com/ScriptReference/PackageManager.PackageInfo.FindForAssembly.html
var packageInfo = PackageManager.PackageInfo.FindForAssembly();
// Finally we have access to the version!
var version = packageInfo.version;
// Now to the ScriptableObject instance
// Try to find the first instance
// See https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
// See https://docs.unity3d.com/ScriptReference/PackageManager.PackageInfo-assetPath.html
var guid = AssetDataBase.FindAssets($"t:{nameof(PackageVersion)}", packageInfo.assetPath). FirstOrDefault();
PackageVersion asset;
if(!string.isNullOrWhiteSpace(guid))
{
// See https://docs.unity3d.com/ScriptReference/AssetDatabase.GUIDToAssetPath.html
var path = AssetDatabase.GUIDToAssetPath(guid);
// See https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
asset = AssetDatabase.LoadAssetAtPath<PackageVersion>(path);                          
}
else
{
// None found -> create a new one
asset = ScriptableObject.CreateInstance<PackageVersion>();
asset.name = nameof(PackageVersion);
// make it non editable via the Inspector
// See https://docs.unity3d.com/ScriptReference/HideFlags.NotEditable.html
asset.hideFlags = HideFlags.NotEditable;
// Store the asset as actually asset
// See https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
AssetDataBase.CreateAsset(asset, $"{packageInfo.assetPath}/{nameof(PackageVersion)}");
}
asset.Version = version;
// See https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html
EditorUtility.SetDirty(asset);
}
#endif
}

现在,只要需要,您就可以引用PackageVersion对象并在运行时访问该版本。


注意:在智能手机上打字,但我希望这个想法能清楚