public IEnumerator InitializationObjects_CompletesWhenObjectsPresent() { if (m_RuntimeSettingsPath.StartsWith("GUID:")) { Debug.Log($"{nameof(InitializationObjects_CompletesWhenObjectsPresent)} skipped due to not having a runtime settings asset (Fast mode does not create this)."); yield break; } InitalizationObjectsOperation op = new InitalizationObjectsOperation(); op.Completed += obj => { Assert.AreEqual(AsyncOperationStatus.Succeeded, obj.Status); Assert.IsTrue(obj.Result); }; var runtimeDataLocation = new ResourceLocationBase("RuntimeData", m_RuntimeSettingsPath, typeof(JsonAssetProvider).FullName, typeof(ResourceManagerRuntimeData)); var rtdOp = m_Addressables.ResourceManager.ProvideResource <ResourceManagerRuntimeData>(runtimeDataLocation); rtdOp.Completed += obj => { ObjectInitializationData opData = ObjectInitializationData.CreateSerializedInitializationData <FakeInitializationObject>("fake", "fake"); obj.Result.InitializationObjects.Add(opData); }; yield return(rtdOp); op.Init(rtdOp, m_Addressables); var handle = m_Addressables.ResourceManager.StartOperation(op, rtdOp); yield return(handle); }
public IEnumerator InitializationObjects_CompletesWhenObjectsPresent() { InitalizationObjectsOperation op = new InitalizationObjectsOperation(); op.Completed += obj => { Assert.AreEqual(AsyncOperationStatus.Succeeded, obj.Status); Assert.IsTrue(obj.Result); }; var runtimeDataLocation = new ResourceLocationBase("RuntimeData", m_RuntimeSettingsPath, typeof(JsonAssetProvider).FullName, typeof(ResourceManagerRuntimeData)); var rtdOp = m_Addressables.ResourceManager.ProvideResource <ResourceManagerRuntimeData>(runtimeDataLocation); rtdOp.Completed += obj => { ObjectInitializationData opData = ObjectInitializationData.CreateSerializedInitializationData <FakeInitializationObject>("fake", "fake"); obj.Result.InitializationObjects.Add(opData); }; yield return(rtdOp); op.Init(rtdOp, m_Addressables); var handle = m_Addressables.ResourceManager.StartOperation(op, rtdOp); yield return(handle); }
/// <inheritdoc /> protected override TResult BuildDataImplementation<TResult>(AddressablesDataBuilderInput context) { TResult result = default(TResult); var timer = new Stopwatch(); timer.Start(); var aaSettings = context.AddressableSettings; PathFormat = context.PathFormat; //create runtime data var aaContext = new AddressableAssetsBuildContext { settings = aaSettings, runtimeData = new ResourceManagerRuntimeData(), bundleToAssetGroup = null, locations = new List<ContentCatalogDataEntry>() }; aaContext.runtimeData.BuildTarget = context.Target.ToString(); aaContext.runtimeData.LogResourceManagerExceptions = aaSettings.buildSettings.LogResourceManagerExceptions; aaContext.runtimeData.ProfileEvents = ProjectConfigData.postProfilerEvents; aaContext.runtimeData.CatalogLocations.Add(new ResourceLocationData(new[] { ResourceManagerRuntimeData.kCatalogAddress }, string.Format(PathFormat, "file://{UnityEngine.Application.dataPath}/../", "catalog"), typeof(ContentCatalogProvider))); var errorString = ProcessAllGroups(aaContext); if(!string.IsNullOrEmpty(errorString)) result = AddressableAssetBuildResult.CreateResult<TResult>(null, 0, errorString); if (result == null) { foreach (var io in aaSettings.InitializationObjects) { if (io is IObjectInitializationDataProvider) aaContext.runtimeData.InitializationObjects.Add((io as IObjectInitializationDataProvider).CreateObjectInitializationData()); } var settingsPath = string.Format(PathFormat, "", "settings"); WriteFile(settingsPath, JsonUtility.ToJson(aaContext.runtimeData)); //save catalog var catalogData = new ContentCatalogData(aaContext.locations); if (m_NeedsLegacyProvider) catalogData.ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(typeof(LegacyResourcesProvider))); catalogData.ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData<AssetDatabaseProvider>()); catalogData.InstanceProviderData = ObjectInitializationData.CreateSerializedInitializationData(instanceProviderType.Value); catalogData.SceneProviderData = ObjectInitializationData.CreateSerializedInitializationData(sceneProviderType.Value); WriteFile(string.Format(PathFormat, "", "catalog"), JsonUtility.ToJson(catalogData)); //inform runtime of the init data path var runtimeSettingsPath = string.Format(PathFormat, "file://{UnityEngine.Application.dataPath}/../", "settings"); PlayerPrefs.SetString(Addressables.kAddressablesRuntimeDataPath, runtimeSettingsPath); result = AddressableAssetBuildResult.CreateResult<TResult>(settingsPath, aaContext.locations.Count); } if(result != null) result.Duration = timer.Elapsed.TotalSeconds; return result; }
protected override void Execute() { var db = GetBuilderOfType <BuildScriptFastMode>(m_settings); if (db == null) { UnityEngine.Debug.Log($"Unable to find {nameof(BuildScriptFastMode)} builder in settings assets. Using default Instance and Scene Providers."); } var locator = new AddressableAssetSettingsLocator(m_settings); m_addressables.AddResourceLocator(locator); m_addressables.AddResourceLocator(new DynamicResourceLocator(m_addressables)); m_addressables.ResourceManager.postProfilerEvents = ProjectConfigData.PostProfilerEvents; if (!m_addressables.ResourceManager.postProfilerEvents) { m_Diagnostics.Dispose(); m_Diagnostics = null; m_addressables.ResourceManager.ClearDiagnosticCallbacks(); } //NOTE: for some reason, the data builders can get lost from the settings asset during a domain reload - this only happens in tests and custom instance and scene providers are not needed m_addressables.InstanceProvider = db == null ? new InstanceProvider() : ObjectInitializationData.CreateSerializedInitializationData(db.instanceProviderType.Value).CreateInstance <IInstanceProvider>(); m_addressables.SceneProvider = db == null ? new SceneProvider() : ObjectInitializationData.CreateSerializedInitializationData(db.sceneProviderType.Value).CreateInstance <ISceneProvider>(); m_addressables.ResourceManager.ResourceProviders.Add(new AssetDatabaseProvider()); m_addressables.ResourceManager.ResourceProviders.Add(new TextDataProvider()); m_addressables.ResourceManager.ResourceProviders.Add(new JsonAssetProvider()); m_addressables.ResourceManager.ResourceProviders.Add(new LegacyResourcesProvider()); m_addressables.ResourceManager.ResourceProviders.Add(new AtlasSpriteProvider()); m_addressables.ResourceManager.ResourceProviders.Add(new ContentCatalogProvider(m_addressables.ResourceManager)); WebRequestQueue.SetMaxConcurrentRequests(m_settings.MaxConcurrentWebRequests); if (m_settings.InitializationObjects.Count == 0) { Complete(locator, true, null); } else { List <AsyncOperationHandle> initOperations = new List <AsyncOperationHandle>(); foreach (var io in m_settings.InitializationObjects) { if (io is IObjectInitializationDataProvider) { var ioData = (io as IObjectInitializationDataProvider).CreateObjectInitializationData(); var h = ioData.GetAsyncInitHandle(m_addressables.ResourceManager); initOperations.Add(h); } } groupOp = m_addressables.ResourceManager.CreateGenericGroupOperation(initOperations, true); groupOp.Completed += op => { bool success = op.Status == AsyncOperationStatus.Succeeded; Complete(locator, success, success ? "" : $"{op.DebugName}, status={op.Status}, result={op.Result} failed initialization."); m_addressables.Release(op); }; } }
internal string ProcessPlayerDataSchema( PlayerDataGroupSchema schema, AddressableAssetGroup assetGroup, AddressableAssetsBuildContext aaContext) { if (CreateLocationsForPlayerData(schema, assetGroup, aaContext.locations, aaContext.providerTypes)) { if (!m_CreatedProviderIds.Contains(typeof(LegacyResourcesProvider).Name)) { m_CreatedProviderIds.Add(typeof(LegacyResourcesProvider).Name); m_ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(typeof(LegacyResourcesProvider))); } } return(string.Empty); }
/// <summary> /// The processing of the bundled asset schema. This is where the bundle(s) for a given group are actually setup. /// </summary> /// <param name="schema">The BundledAssetGroupSchema to process</param> /// <param name="assetGroup">The group this schema was pulled from</param> /// <param name="aaContext">The general Addressables build builderInput</param> /// <returns>The error string, if any.</returns> protected virtual string ProcessBundledAssetSchema( BundledAssetGroupSchema schema, AddressableAssetGroup assetGroup, AddressableAssetsBuildContext aaContext) { if (schema == null || !schema.IncludeInBuild || !assetGroup.entries.Any()) { return(string.Empty); } var errorStr = ErrorCheckBundleSettings(schema, assetGroup, aaContext.settings); if (!string.IsNullOrEmpty(errorStr)) { return(errorStr); } var bundledProviderId = schema.GetBundleCachedProviderId(); var assetProviderId = schema.GetAssetCachedProviderId(); if (!m_CreatedProviderIds.Contains(bundledProviderId)) { m_CreatedProviderIds.Add(bundledProviderId); var bundleProviderType = schema.AssetBundleProviderType.Value; var bundleProviderData = ObjectInitializationData.CreateSerializedInitializationData(bundleProviderType, bundledProviderId); m_ResourceProviderData.Add(bundleProviderData); } if (!m_CreatedProviderIds.Contains(assetProviderId)) { m_CreatedProviderIds.Add(assetProviderId); var assetProviderType = schema.BundledAssetProviderType.Value; var assetProviderData = ObjectInitializationData.CreateSerializedInitializationData(assetProviderType, assetProviderId); m_ResourceProviderData.Add(assetProviderData); } var bundleInputDefs = new List <AssetBundleBuild>(); PrepGroupBundlePacking(assetGroup, bundleInputDefs, schema.BundleMode); HandleDuplicateBundleNames(bundleInputDefs, aaContext.bundleToAssetGroup, assetGroup.Guid, out var uniqueNames); m_OutputAssetBundleNames.AddRange(uniqueNames); m_AllBundleInputDefs.AddRange(bundleInputDefs); return(string.Empty); }
static void LoadProvider(AddressablesImpl addressables, ObjectInitializationData providerData, string providerSuffix) { //don't add providers that have the same id... var indexOfExistingProvider = -1; var newProviderId = string.IsNullOrEmpty(providerSuffix) ? providerData.Id : (providerData.Id + providerSuffix); for (int i = 0; i < addressables.ResourceManager.ResourceProviders.Count; i++) { var rp = addressables.ResourceManager.ResourceProviders[i]; if (rp.ProviderId == newProviderId) { indexOfExistingProvider = i; break; } } //if not re-initializing, just use the old provider if (indexOfExistingProvider >= 0 && string.IsNullOrEmpty(providerSuffix)) { return; } var provider = providerData.CreateInstance <IResourceProvider>(newProviderId); if (provider != null) { if (indexOfExistingProvider < 0 || !string.IsNullOrEmpty(providerSuffix)) { Addressables.LogFormat("Addressables - added provider {0} with id {1}.", provider, provider.ProviderId); addressables.ResourceManager.ResourceProviders.Add(provider); } else { Addressables.LogFormat("Addressables - replacing provider {0} at index {1}.", provider, indexOfExistingProvider); addressables.ResourceManager.ResourceProviders[indexOfExistingProvider] = provider; } } else { Addressables.LogWarningFormat("Addressables - Unable to load resource provider from {0}.", providerData); } }
/// <summary> /// The method that does the actual building after all the groups have been processed. /// </summary> /// <param name="builderInput">The generic builderInput of the</param> /// <param name="aaContext"></param> /// <typeparam name="TResult"></typeparam> /// <returns></returns> protected virtual TResult DoBuild <TResult>(AddressablesDataBuilderInput builderInput, AddressableAssetsBuildContext aaContext) where TResult : IDataBuilderResult { ExtractDataTask extractData = new ExtractDataTask(); var tempPath = Path.GetDirectoryName(Application.dataPath) + "/Library/com.unity.addressables/StreamingAssetsCopy/" + PlatformMappingService.GetPlatform() + "/addressables_content_state.bin"; var playerBuildVersion = builderInput.PlayerVersion; if (m_AllBundleInputDefs.Count > 0) { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return(AddressableAssetBuildResult.CreateResult <TResult>(null, 0, "Unsaved scenes")); } var buildTarget = builderInput.Target; var buildTargetGroup = builderInput.TargetGroup; var buildParams = new AddressableAssetsBundleBuildParameters( aaContext.settings, aaContext.bundleToAssetGroup, buildTarget, buildTargetGroup, aaContext.settings.buildSettings.bundleBuildPath); var builtinShaderBundleName = aaContext.settings.DefaultGroup.Name.ToLower().Replace(" ", "").Replace('\\', '/').Replace("//", "/") + "_unitybuiltinshaders.bundle"; var buildTasks = RuntimeDataBuildTasks(builtinShaderBundleName); buildTasks.Add(extractData); string aaPath = aaContext.settings.AssetPath; IBundleBuildResults results; var exitCode = ContentPipeline.BuildAssetBundles(buildParams, new BundleBuildContent(m_AllBundleInputDefs), out results, buildTasks, aaContext); if (exitCode < ReturnCode.Success) { return(AddressableAssetBuildResult.CreateResult <TResult>(null, 0, "SBP Error" + exitCode)); } if (aaContext.settings == null && !string.IsNullOrEmpty(aaPath)) { aaContext.settings = AssetDatabase.LoadAssetAtPath <AddressableAssetSettings>(aaPath); } GenerateLocationListsTask.Run(aaContext, extractData.WriteData); foreach (var assetGroup in aaContext.settings.groups) { List <string> bundles; if (aaContext.assetGroupToBundles.TryGetValue(assetGroup, out bundles)) { PostProcessBundles(assetGroup, bundles, results, extractData.WriteData, aaContext.runtimeData, aaContext.locations, builderInput.Registry); PostProcessCatalogEnteries(assetGroup, extractData.WriteData, aaContext.locations, builderInput.Registry); } } foreach (var r in results.WriteResults) { m_Linker.AddTypes(r.Value.includedTypes); } } //save catalog var contentCatalog = new ContentCatalogData(aaContext.locations); contentCatalog.ResourceProviderData.AddRange(m_ResourceProviderData); foreach (var t in aaContext.providerTypes) { contentCatalog.ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(t)); } contentCatalog.InstanceProviderData = ObjectInitializationData.CreateSerializedInitializationData(instanceProviderType.Value); contentCatalog.SceneProviderData = ObjectInitializationData.CreateSerializedInitializationData(sceneProviderType.Value); CreateCatalog(aaContext.settings, contentCatalog, aaContext.runtimeData.CatalogLocations, playerBuildVersion, builderInput.RuntimeCatalogFilename, builderInput.Registry); foreach (var pd in contentCatalog.ResourceProviderData) { m_Linker.AddTypes(pd.ObjectType.Value); m_Linker.AddTypes(pd.GetRuntimeTypes()); } m_Linker.AddTypes(contentCatalog.InstanceProviderData.ObjectType.Value); m_Linker.AddTypes(contentCatalog.InstanceProviderData.GetRuntimeTypes()); m_Linker.AddTypes(contentCatalog.SceneProviderData.ObjectType.Value); m_Linker.AddTypes(contentCatalog.SceneProviderData.GetRuntimeTypes()); foreach (var io in aaContext.settings.InitializationObjects) { var provider = io as IObjectInitializationDataProvider; if (provider != null) { var id = provider.CreateObjectInitializationData(); aaContext.runtimeData.InitializationObjects.Add(id); m_Linker.AddTypes(id.ObjectType.Value); m_Linker.AddTypes(id.GetRuntimeTypes()); } } m_Linker.AddTypes(typeof(Addressables)); m_Linker.Save(Addressables.BuildPath + "/link.xml"); var settingsPath = Addressables.BuildPath + "/" + builderInput.RuntimeSettingsFilename; WriteFile(settingsPath, JsonUtility.ToJson(aaContext.runtimeData), builderInput.Registry); var opResult = AddressableAssetBuildResult.CreateResult <TResult>(settingsPath, aaContext.locations.Count); //save content update data if building for the player var allEntries = new List <AddressableAssetEntry>(); aaContext.settings.GetAllAssets(allEntries, false, g => g.HasSchema <ContentUpdateGroupSchema>() && g.GetSchema <ContentUpdateGroupSchema>().StaticContent); var remoteCatalogLoadPath = aaContext.settings.BuildRemoteCatalog ? aaContext.settings.RemoteCatalogLoadPath.GetValue(aaContext.settings) : string.Empty; if (extractData.BuildCache != null && ContentUpdateScript.SaveContentState(aaContext.locations, tempPath, allEntries, extractData.DependencyData, playerBuildVersion, remoteCatalogLoadPath)) { try { File.Copy(tempPath, ContentUpdateScript.GetContentStateDataPath(false), true); } catch (Exception e) { Debug.LogException(e); } } return(opResult); }
/// <summary> /// TBD /// </summary> protected override CustomDirectory CreateObject(ObjectInitializationData data) { return(new CustomDirectory(data)); }
/// <summary> /// Создаёт объект с указанными начальными данными /// </summary> protected override MainInfo CreateObject(ObjectInitializationData data) { return(new MainInfo(data)); }
/// <inheritdoc /> protected override string ProcessGroup(AddressableAssetGroup assetGroup, AddressableAssetsBuildContext aaContext) { var errorString = string.Empty; PlayerDataGroupSchema playerSchema = assetGroup.GetSchema <PlayerDataGroupSchema>(); if (playerSchema != null) { if (CreateLocationsForPlayerData(playerSchema, assetGroup, aaContext.locations, aaContext.providerTypes)) { if (!m_CreatedProviderIds.ContainsKey(typeof(LegacyResourcesProvider).Name)) { m_CreatedProviderIds.Add(typeof(LegacyResourcesProvider).Name, null); m_ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(typeof(LegacyResourcesProvider))); } } return(errorString); } var schema = assetGroup.GetSchema <BundledAssetGroupSchema>(); if (schema == null) { return(errorString); } var bundledProviderId = schema.GetBundleCachedProviderId(); var assetProviderId = schema.GetAssetCachedProviderId(); if (!m_CreatedProviderIds.ContainsKey(bundledProviderId)) { //TODO: pull from schema instead of ProjectConfigData var virtualBundleRuntimeData = new VirtualAssetBundleRuntimeData(ProjectConfigData.localLoadSpeed, ProjectConfigData.remoteLoadSpeed); //save virtual runtime data to collect assets into virtual bundles m_CreatedProviderIds.Add(bundledProviderId, virtualBundleRuntimeData); } if (!m_CreatedProviderIds.ContainsKey(assetProviderId)) { m_CreatedProviderIds.Add(assetProviderId, null); var assetProviderData = ObjectInitializationData.CreateSerializedInitializationData <VirtualBundledAssetProvider>(assetProviderId); m_ResourceProviderData.Add(assetProviderData); } var bundleInputDefs = new List <AssetBundleBuild>(); BuildScriptPackedMode.PrepGroupBundlePacking(assetGroup, bundleInputDefs, schema.BundleMode); for (int i = 0; i < bundleInputDefs.Count; i++) { if (aaContext.bundleToAssetGroup.ContainsKey(bundleInputDefs[i].assetBundleName)) { var bid = bundleInputDefs[i]; int count = 1; var newName = bid.assetBundleName; while (aaContext.bundleToAssetGroup.ContainsKey(newName) && count < 1000) { newName = bid.assetBundleName.Replace(".bundle", string.Format("{0}.bundle", count++)); } bundleInputDefs[i] = new AssetBundleBuild { assetBundleName = newName, addressableNames = bid.addressableNames, assetBundleVariant = bid.assetBundleVariant, assetNames = bid.assetNames }; } aaContext.bundleToAssetGroup.Add(bundleInputDefs[i].assetBundleName, assetGroup.Guid); } m_AllBundleInputDefinitions.AddRange(bundleInputDefs); return(errorString); }
/// <summary> /// The method that does the actual building after all the groups have been processed. /// </summary> /// <param name="builderInput">The generic builderInput of the</param> /// <param name="aaContext"></param> /// <typeparam name="TResult"></typeparam> /// <returns></returns> protected virtual TResult DoBuild <TResult>(AddressablesDataBuilderInput builderInput, AddressableAssetsBuildContext aaContext) where TResult : IDataBuilderResult { ExtractDataTask extractData = new ExtractDataTask(); List <CachedAssetState> carryOverCachedState = new List <CachedAssetState>(); var tempPath = Path.GetDirectoryName(Application.dataPath) + "/Library/com.unity.addressables/StreamingAssetsCopy/" + PlatformMappingService.GetPlatform() + "/addressables_content_state.bin"; var playerBuildVersion = builderInput.PlayerVersion; if (m_AllBundleInputDefs.Count > 0) { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return(AddressableAssetBuildResult.CreateResult <TResult>(null, 0, "Unsaved scenes")); } var buildTarget = builderInput.Target; var buildTargetGroup = builderInput.TargetGroup; var buildParams = new AddressableAssetsBundleBuildParameters( aaContext.settings, aaContext.bundleToAssetGroup, buildTarget, buildTargetGroup, aaContext.settings.buildSettings.bundleBuildPath); var builtinShaderBundleName = aaContext.settings.DefaultGroup.Guid + "_unitybuiltinshaders.bundle"; var buildTasks = RuntimeDataBuildTasks(builtinShaderBundleName); buildTasks.Add(extractData); string aaPath = aaContext.settings.AssetPath; IBundleBuildResults results; using (m_Log.ScopedStep(LogLevel.Info, "ContentPipeline.BuildAssetBundles")) { var exitCode = ContentPipeline.BuildAssetBundles(buildParams, new BundleBuildContent(m_AllBundleInputDefs), out results, buildTasks, aaContext, m_Log); if (exitCode < ReturnCode.Success) { return(AddressableAssetBuildResult.CreateResult <TResult>(null, 0, "SBP Error" + exitCode)); } } if (aaContext.settings == null && !string.IsNullOrEmpty(aaPath)) { aaContext.settings = AssetDatabase.LoadAssetAtPath <AddressableAssetSettings>(aaPath); } using (var progressTracker = new UnityEditor.Build.Pipeline.Utilities.ProgressTracker()) using (m_Log.ScopedStep(LogLevel.Info, "GenerateLocationListsTask.Run")) { progressTracker.UpdateTask("Generating Addressables Locations"); GenerateLocationListsTask.Run(aaContext, extractData.WriteData); } var groups = aaContext.settings.groups.Where(g => g != null); using (m_Log.ScopedStep(LogLevel.Info, "PostProcessBundles")) using (var progressTracker = new UnityEditor.Build.Pipeline.Utilities.ProgressTracker()) { progressTracker.UpdateTask("Post Processing AssetBundles"); Dictionary <string, ContentCatalogDataEntry> primaryKeyToCatalogEntry = new Dictionary <string, ContentCatalogDataEntry>(); foreach (var loc in aaContext.locations) { if (loc != null && loc.Keys[0] != null && loc.Keys[0] is string && !primaryKeyToCatalogEntry.ContainsKey((string)loc.Keys[0])) { primaryKeyToCatalogEntry[(string)loc.Keys[0]] = loc; } } foreach (var assetGroup in groups) { if (aaContext.assetGroupToBundles.TryGetValue(assetGroup, out List <string> buildBundles)) { List <string> outputBundles = new List <string>(); for (int i = 0; i < buildBundles.Count; ++i) { var b = m_AllBundleInputDefs.FindIndex(inputDef => buildBundles[i].StartsWith(inputDef.assetBundleName)); outputBundles.Add(b >= 0 ? m_OutputAssetBundleNames[b] : buildBundles[i]); } PostProcessBundles(assetGroup, buildBundles, outputBundles, results, extractData.WriteData, aaContext.runtimeData, aaContext.locations, builderInput.Registry, primaryKeyToCatalogEntry); } } } ProcessCatalogEntriesForBuild(aaContext, m_Log, groups, builderInput, extractData.WriteData, carryOverCachedState, m_BundleToInternalId); foreach (var r in results.WriteResults) { m_Linker.AddTypes(r.Value.includedTypes); } } var contentCatalog = new ContentCatalogData(aaContext.locations, ResourceManagerRuntimeData.kCatalogAddress); contentCatalog.ResourceProviderData.AddRange(m_ResourceProviderData); foreach (var t in aaContext.providerTypes) { contentCatalog.ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(t)); } contentCatalog.InstanceProviderData = ObjectInitializationData.CreateSerializedInitializationData(instanceProviderType.Value); contentCatalog.SceneProviderData = ObjectInitializationData.CreateSerializedInitializationData(sceneProviderType.Value); //save catalog var jsonText = JsonUtility.ToJson(contentCatalog); CreateCatalogFiles(jsonText, builderInput, aaContext); foreach (var pd in contentCatalog.ResourceProviderData) { m_Linker.AddTypes(pd.ObjectType.Value); m_Linker.AddTypes(pd.GetRuntimeTypes()); } m_Linker.AddTypes(contentCatalog.InstanceProviderData.ObjectType.Value); m_Linker.AddTypes(contentCatalog.InstanceProviderData.GetRuntimeTypes()); m_Linker.AddTypes(contentCatalog.SceneProviderData.ObjectType.Value); m_Linker.AddTypes(contentCatalog.SceneProviderData.GetRuntimeTypes()); foreach (var io in aaContext.settings.InitializationObjects) { var provider = io as IObjectInitializationDataProvider; if (provider != null) { var id = provider.CreateObjectInitializationData(); aaContext.runtimeData.InitializationObjects.Add(id); m_Linker.AddTypes(id.ObjectType.Value); m_Linker.AddTypes(id.GetRuntimeTypes()); } } m_Linker.AddTypes(typeof(Addressables)); m_Linker.Save(Addressables.BuildPath + "/link.xml"); var settingsPath = Addressables.BuildPath + "/" + builderInput.RuntimeSettingsFilename; WriteFile(settingsPath, JsonUtility.ToJson(aaContext.runtimeData), builderInput.Registry); var opResult = AddressableAssetBuildResult.CreateResult <TResult>(settingsPath, aaContext.locations.Count); //save content update data if building for the player var allEntries = new List <AddressableAssetEntry>(); aaContext.settings.GetAllAssets(allEntries, false, g => g != null && g.HasSchema <ContentUpdateGroupSchema>() && g.GetSchema <ContentUpdateGroupSchema>().StaticContent); var remoteCatalogLoadPath = aaContext.settings.BuildRemoteCatalog ? aaContext.settings.RemoteCatalogLoadPath.GetValue(aaContext.settings) : string.Empty; if (extractData.BuildCache != null && ContentUpdateScript.SaveContentState(aaContext.locations, tempPath, allEntries, extractData.DependencyData, playerBuildVersion, remoteCatalogLoadPath, carryOverCachedState)) { try { var contentStatePath = ContentUpdateScript.GetContentStateDataPath(false); File.Copy(tempPath, contentStatePath, true); builderInput.Registry.AddFile(contentStatePath); } catch (Exception e) { Debug.LogException(e); } } return(opResult); }
protected override TResult BuildDataImplementation <TResult>(AddressablesDataBuilderInput context) { TResult result = default(TResult); var aaSettings = context.AddressableSettings; //create runtime data var aaContext = new AddressableAssetsBuildContext { Settings = aaSettings, runtimeData = new ResourceManagerRuntimeData(), bundleToAssetGroup = null, locations = new List <ContentCatalogDataEntry>(), providerTypes = new HashSet <Type>() }; aaContext.runtimeData.BuildTarget = context.Target.ToString(); aaContext.runtimeData.LogResourceManagerExceptions = aaSettings.buildSettings.LogResourceManagerExceptions; aaContext.runtimeData.CatalogLocations.Add(new ResourceLocationData( new[] { ResourceManagerRuntimeData.kCatalogAddress }, string.Format(PathFormat, "file://{UnityEngine.Application.dataPath}/../", "catalog"), typeof(ContentCatalogProvider), typeof(ContentCatalogData))); var errorString = ProcessAllGroups(aaContext); if (!string.IsNullOrEmpty(errorString)) { result = AddressableAssetBuildResult.CreateResult <TResult>(null, 0, errorString); } if (result == null) { foreach (var io in aaSettings.InitializationObjects) { if (io is IObjectInitializationDataProvider) { var initData = (io as IObjectInitializationDataProvider) .CreateObjectInitializationData(); aaContext .runtimeData .InitializationObjects .Add(initData); } } var settingsPath = string.Format(PathFormat, "", "settings"); WriteFile(settingsPath, JsonUtility.ToJson(aaContext.runtimeData), context.Registry); //save catalog var catalogData = new ContentCatalogData( aaContext.locations, ResourceManagerRuntimeData.kCatalogAddress); foreach (var t in aaContext.providerTypes) { var provider = ObjectInitializationData.CreateSerializedInitializationData(t); catalogData.ResourceProviderData.Add(provider); } catalogData.ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData <AssetDatabaseProvider>()); catalogData.InstanceProviderData = ObjectInitializationData.CreateSerializedInitializationData(instanceProviderType.Value); catalogData.SceneProviderData = ObjectInitializationData.CreateSerializedInitializationData(sceneProviderType.Value); WriteFile(string.Format(PathFormat, "", "catalog"), JsonUtility.ToJson(catalogData), context.Registry); //inform runtime of the init data path var runtimeSettingsPath = string.Format(PathFormat, "file://{UnityEngine.Application.dataPath}/../", "settings"); PlayerPrefs.SetString(Addressables.kAddressablesRuntimeDataPath, runtimeSettingsPath); result = AddressableAssetBuildResult.CreateResult <TResult>(settingsPath, aaContext.locations.Count); } return(result); }
TResult DoBuild <TResult>(AddressablesDataBuilderInput builderInput, AddressableAssetSettings aaSettings, AddressableAssetsBuildContext aaContext) where TResult : IDataBuilderResult { if (m_AllBundleInputDefinitions.Count > 0) { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return(AddressableAssetBuildResult.CreateResult <TResult>(null, 0, "Unsaved scenes")); } var buildTarget = builderInput.Target; var buildTargetGroup = builderInput.TargetGroup; var buildParams = new AddressableAssetsBundleBuildParameters(aaSettings, aaContext.bundleToAssetGroup, buildTarget, buildTargetGroup, aaSettings.buildSettings.bundleBuildPath); var builtinShaderBundleName = aaSettings.DefaultGroup.Name.ToLower().Replace(" ", "").Replace('\\', '/').Replace("//", "/") + "_unitybuiltinshaders.bundle"; var buildTasks = RuntimeDataBuildTasks(aaSettings.buildSettings.compileScriptsInVirtualMode, builtinShaderBundleName); ExtractDataTask extractData = new ExtractDataTask(); buildTasks.Add(extractData); string aaPath = aaSettings.AssetPath; IBundleBuildResults results; var exitCode = ContentPipeline.BuildAssetBundles(buildParams, new BundleBuildContent(m_AllBundleInputDefinitions), out results, buildTasks, aaContext); if (exitCode < ReturnCode.Success) { return(AddressableAssetBuildResult.CreateResult <TResult>(null, 0, "SBP Error" + exitCode)); } if (aaSettings == null && !string.IsNullOrEmpty(aaPath)) { aaSettings = AssetDatabase.LoadAssetAtPath <AddressableAssetSettings>(aaPath); } } var bundledAssets = new Dictionary <object, HashSet <string> >(); foreach (var loc in aaContext.locations) { if (loc.Dependencies != null && loc.Dependencies.Count > 0) { for (int i = 0; i < loc.Dependencies.Count; i++) { var dep = loc.Dependencies[i]; HashSet <string> assetsInBundle; if (!bundledAssets.TryGetValue(dep, out assetsInBundle)) { bundledAssets.Add(dep, assetsInBundle = new HashSet <string>()); } if (i == 0 && !assetsInBundle.Contains(loc.InternalId)) //only add the asset to the first bundle... { assetsInBundle.Add(loc.InternalId); } } } } foreach (var bd in bundledAssets) { AddressableAssetGroup group = aaSettings.DefaultGroup; string groupGuid; if (aaContext.bundleToAssetGroup.TryGetValue(bd.Key as string, out groupGuid)) { group = aaSettings.FindGroup(g => g.Guid == groupGuid); } var schema = group.GetSchema <BundledAssetGroupSchema>(); if (schema != null) { var bundleLocData = aaContext.locations.First(s => s.Keys[0] == bd.Key); var isLocalBundle = IsInternalIdLocal(bundleLocData.InternalId); uint crc = (uint)UnityEngine.Random.Range(0, int.MaxValue); var hash = Guid.NewGuid().ToString(); string originalBundleName = bd.Key as string; string newBundleName = BuildUtility.GetNameWithHashNaming(schema.BundleNaming, hash, originalBundleName); bundleLocData.InternalId = bundleLocData.InternalId.Remove(bundleLocData.InternalId.Length - originalBundleName.Length) + newBundleName; var virtualBundleName = AddressablesRuntimeProperties.EvaluateString(bundleLocData.InternalId); var bundleData = new VirtualAssetBundle(virtualBundleName, isLocalBundle, crc, hash); long dataSize = 0; long headerSize = 0; foreach (var a in bd.Value) { var size = ComputeSize(a); bundleData.Assets.Add(new VirtualAssetBundleEntry(a, size)); dataSize += size; headerSize += a.Length * 5; //assume 5x path length overhead size per item, probably much less } if (bd.Value.Count == 0) { dataSize = 100 * 1024; headerSize = 1024; } bundleData.SetSize(dataSize, headerSize); var requestOptions = new VirtualAssetBundleRequestOptions { Crc = schema.UseAssetBundleCrc ? crc : 0, Hash = schema.UseAssetBundleCache ? hash : "", ChunkedTransfer = schema.ChunkedTransfer, RedirectLimit = schema.RedirectLimit, RetryCount = schema.RetryCount, Timeout = schema.Timeout, BundleName = Path.GetFileName(bundleLocData.InternalId), BundleSize = dataSize + headerSize }; bundleLocData.Data = requestOptions; var bundleProviderId = schema.GetBundleCachedProviderId(); var virtualBundleRuntimeData = m_CreatedProviderIds[bundleProviderId]; virtualBundleRuntimeData.AssetBundles.Add(bundleData); } } foreach (var kvp in m_CreatedProviderIds) { if (kvp.Value != null) { var bundleProviderData = ObjectInitializationData.CreateSerializedInitializationData <VirtualAssetBundleProvider>(kvp.Key, kvp.Value); m_ResourceProviderData.Add(bundleProviderData); } } var contentCatalog = new ContentCatalogData(aaContext.locations, ResourceManagerRuntimeData.kCatalogAddress); contentCatalog.ResourceProviderData.AddRange(m_ResourceProviderData); foreach (var t in aaContext.providerTypes) { contentCatalog.ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(t)); } contentCatalog.InstanceProviderData = ObjectInitializationData.CreateSerializedInitializationData(instanceProviderType.Value); contentCatalog.SceneProviderData = ObjectInitializationData.CreateSerializedInitializationData(sceneProviderType.Value); //save catalog WriteFile(string.Format(m_PathFormat, "", "catalog"), JsonUtility.ToJson(contentCatalog), builderInput.Registry); foreach (var io in aaSettings.InitializationObjects) { if (io is IObjectInitializationDataProvider) { aaContext.runtimeData.InitializationObjects.Add((io as IObjectInitializationDataProvider).CreateObjectInitializationData()); } } var settingsPath = string.Format(m_PathFormat, "", "settings"); WriteFile(settingsPath, JsonUtility.ToJson(aaContext.runtimeData), builderInput.Registry); //inform runtime of the init data path var runtimeSettingsPath = string.Format(m_PathFormat, "file://{UnityEngine.Application.dataPath}/../", "settings"); PlayerPrefs.SetString(Addressables.kAddressablesRuntimeDataPath, runtimeSettingsPath); var result = AddressableAssetBuildResult.CreateResult <TResult>(settingsPath, aaContext.locations.Count); return(result); }
/// <summary> /// Create initialization data to be serialized into the Addressables runtime data. /// </summary> /// <returns>The serialized data for the initialization class and the data.</returns> public ObjectInitializationData CreateObjectInitializationData() { return(ObjectInitializationData.CreateSerializedInitializationData <PlayAssetDeliveryInitialization>(typeof(PlayAssetDeliveryInitialization).Name, m_Data)); }
/// <summary> /// The processing of the bundled asset schema. This is where the bundle(s) for a given group are actually setup. /// </summary> /// <param name="schema">The BundledAssetGroupSchema to process</param> /// <param name="assetGroup">The group this schema was pulled from</param> /// <param name="aaContext">The general Addressables build builderInput</param> /// <returns>The error string, if any.</returns> protected virtual string ProcessBundledAssetSchema( BundledAssetGroupSchema schema, AddressableAssetGroup assetGroup, AddressableAssetsBuildContext aaContext) { if (schema == null || !schema.IncludeInBuild) { return(string.Empty); } var errorStr = ErrorCheckBundleSettings(schema, assetGroup, aaContext.settings); if (!string.IsNullOrEmpty(errorStr)) { return(errorStr); } var bundledProviderId = schema.GetBundleCachedProviderId(); var assetProviderId = schema.GetAssetCachedProviderId(); if (!m_CreatedProviderIds.Contains(bundledProviderId)) { m_CreatedProviderIds.Add(bundledProviderId); var bundleProviderType = schema.AssetBundleProviderType.Value; var bundleProviderData = ObjectInitializationData.CreateSerializedInitializationData(bundleProviderType, bundledProviderId); m_ResourceProviderData.Add(bundleProviderData); } if (!m_CreatedProviderIds.Contains(assetProviderId)) { m_CreatedProviderIds.Add(assetProviderId); var assetProviderType = schema.BundledAssetProviderType.Value; var assetProviderData = ObjectInitializationData.CreateSerializedInitializationData(assetProviderType, assetProviderId); m_ResourceProviderData.Add(assetProviderData); } var bundleInputDefs = new List <AssetBundleBuild>(); PrepGroupBundlePacking(assetGroup, bundleInputDefs, schema.BundleMode); for (int i = 0; i < bundleInputDefs.Count; i++) { if (aaContext.bundleToAssetGroup.ContainsKey(bundleInputDefs[i].assetBundleName)) { var bid = bundleInputDefs[i]; int count = 1; var newName = bid.assetBundleName; while (aaContext.bundleToAssetGroup.ContainsKey(newName) && count < 1000) { newName = bid.assetBundleName.Replace(".bundle", string.Format("{0}.bundle", count++)); } bundleInputDefs[i] = new AssetBundleBuild { assetBundleName = newName, addressableNames = bid.addressableNames, assetBundleVariant = bid.assetBundleVariant, assetNames = bid.assetNames }; } aaContext.bundleToAssetGroup.Add(bundleInputDefs[i].assetBundleName, assetGroup.Guid); } m_AllBundleInputDefs.AddRange(bundleInputDefs); return(string.Empty); }
/// <summary> /// Создаёт новый экземпляр <see cref="MainInfo"/> с указанными данными /// </summary> internal MainInfo(ObjectInitializationData data) : base(data) { }
/// <summary> /// Создаёт новый экземпляр <see cref="CustomDirectory"/> /// </summary> internal protected CustomDirectory(ObjectInitializationData data) : base(data) { }
/// <summary> /// Create initialization data to be serialized into the Addressables runtime data. /// </summary> /// <returns>The serialized data for the initialization class and the data.</returns> public ObjectInitializationData CreateObjectInitializationData() { return(ObjectInitializationData.CreateSerializedInitializationData <CacheInitialization>(typeof(CacheInitialization).Name, m_Data)); }