public void Show(AddressableAssetSettings settings, List <AddressableAssetEntry> entries) { m_Settings = settings; m_Entries = entries; Show(); }
static AddressableAssetGroup CreateAssetGroup <SchemaType>(AddressableAssetSettings settings, string groupName) { return(settings.CreateGroup(groupName, false, false, false, new List <AddressableAssetGroupSchema> { settings.DefaultGroup.Schemas[0] }, typeof(SchemaType))); }
/// <summary> /// Get a Dictionary of all modified values and their dependencies. Dependencies will be Addressable and part of a group /// with static content enabled. /// </summary> /// <param name="settings">Addressable asset settings.</param> /// <param name="cachePath">The cache data path.</param> /// <returns>A dictionary mapping explicit changed entries to their dependencies.</returns> public static Dictionary <AddressableAssetEntry, List <AddressableAssetEntry> > GatherModifiedEntriesWithDependencies(AddressableAssetSettings settings, string cachePath) { var modifiedData = new Dictionary <AddressableAssetEntry, List <AddressableAssetEntry> >(); AddressablesContentState cacheData = LoadContentState(cachePath); if (cacheData == null) { return(modifiedData); } GatherExplicitModifiedEntries(settings, ref modifiedData, cacheData); GetStaticContentDependenciesForEntries(settings, ref modifiedData, GetGroupGuidToCacheBundleNameMap(cacheData)); return(modifiedData); }
AddressableAssetGroup FindOrCopyGroup(string groupName, AddressableAssetGroup baseGroup, AddressableAssetSettings settings, TextureVariationSchema schema) { AddressableAssetGroup result; if (!m_GeneratedGroups.TryGetValue(groupName, out result)) { List <AddressableAssetGroupSchema> schemas = new List <AddressableAssetGroupSchema>(baseGroup.Schemas); schemas.Remove(schema); result = settings.CreateGroup(groupName, false, false, false, schemas); m_GeneratedGroups.Add(groupName, result); } return(result); }
static AddressableAssetEntry CreateOrUpdateAddressableAssetEntry( AddressableAssetSettings settings, AddressableImportSettings importSettings, AddressableImportRule rule, string assetPath) { // Set group AddressableAssetGroup group; var groupName = rule.ParseGroupReplacement(assetPath); bool newGroup = false; if (!TryGetGroup(settings, groupName, out group)) { if (importSettings.allowGroupCreation) { //TODO Specify on editor which type to create. group = CreateAssetGroup(settings, groupName); newGroup = true; } else { Debug.LogErrorFormat("[AddressableImporter] Failed to find group {0} when importing {1}. Please check if the group exists, then reimport the asset.", rule.groupName, assetPath); return(null); } } // Set group settings from template if necessary if (rule.groupTemplate != null && (newGroup || rule.groupTemplateApplicationMode == GroupTemplateApplicationMode.AlwaysOverwriteGroupSettings)) { rule.groupTemplate.ApplyToAddressableAssetGroup(group); } var guid = AssetDatabase.AssetPathToGUID(assetPath); var entry = group.GetAssetEntry(guid); if (entry == null) { entry = settings.CreateOrMoveEntry(guid, group); } if (entry != null) { if (rule.LabelMode == LabelWriteMode.Replace) { entry.labels.Clear(); } foreach (var label in rule.labels) { entry.labels.Add(label); } // Apply address replacement if address is empty or path. if (string.IsNullOrEmpty(entry.address) || entry.address.StartsWith("Assets/") || rule.simplified || !string.IsNullOrWhiteSpace(rule.addressReplacement) ) { var newPath = rule.ParseAddressReplacement(assetPath); if (entry.address.Equals(newPath)) { return(null); } entry.address = newPath; } } return(entry); }
public LabelNamePopup(float rowHeight, AddressableAssetSettings settings) { this.rowHeight = rowHeight; this.settings = settings; name = this.settings.labelTable.GetUniqueLabelName("New Label"); }
public ProfileNewVariablePopup(float width, float height, float xOffset, ProfileTreeView profileTreeView, AddressableAssetSettings settings) { m_WindowWidth = width; m_WindowHeight = height; m_xOffset = xOffset; m_Settings = settings; m_Name = m_Settings.profileSettings.GetUniqueProfileEntryName("New Entry"); m_Value = Application.dataPath; m_ProfileTreeView = profileTreeView; }
/// <summary> /// This method runs the actual analysis for the rule. /// </summary> /// <param name="settings">The settings object to analyze</param> /// <returns>A list of resulting information (warnings, errors, or info)</returns> public virtual List <AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings) { return(new List <AnalyzeResult>()); }
/// <summary> /// Fixing method to be run on results of the RefreshAnalysis. If CanFix returns true, this method must be /// overriden. It is recommended that RefreshAnalysis caches any data that will be needed to fix. Fix should /// not rerun RefreshAnalysis before fixing. /// </summary> /// <param name="settings">The settings object to analyze</param> public virtual void FixIssues(AddressableAssetSettings settings) { }
public void Build(SpaceNode rootNode, DisposableList <HLODBuildInfo> infos, GameObject root, float cullDistance, float lodDistance, bool writeNoPrefab, bool extractMaterial, Action <float> onProgress) { dynamic options = m_streamingOptions; string path = options.OutputDirectory; HLODTreeNodeContainer container = new HLODTreeNodeContainer(); HLODTreeNode convertedRootNode = ConvertNode(container, rootNode); //create settings if there is no settings. if (AddressableAssetSettingsDefaultObject.Settings == null) { AddressableAssetSettings.Create(AddressableAssetSettingsDefaultObject.kDefaultConfigFolder, AddressableAssetSettingsDefaultObject.kDefaultConfigAssetName, true, true); } var settings = AddressableAssetSettingsDefaultObject.GetSettings(true); var group = GetGroup(settings, options.AddressablesGroupName); m_shaderGuids.Clear(); if (onProgress != null) { onProgress(0.0f); } HLODData.TextureCompressionData compressionData; compressionData.PCTextureFormat = options.PCCompression; compressionData.WebGLTextureFormat = options.WebGLCompression; compressionData.AndroidTextureFormat = options.AndroidCompression; compressionData.iOSTextureFormat = options.iOSCompression; compressionData.tvOSTextureFormat = options.tvOSCompression; string filenamePrefix = $"{path}{root.name}"; if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } Dictionary <int, HLODData> hlodDatas = new Dictionary <int, HLODData>(); for (int i = 0; i < infos.Count; ++i) { if (hlodDatas.ContainsKey(infos[i].ParentIndex) == false) { HLODData newData = new HLODData(); newData.CompressionData = compressionData; hlodDatas.Add(infos[i].ParentIndex, newData); } HLODData data = hlodDatas[infos[i].ParentIndex]; data.AddFromWokringObjects(infos[i].Name, infos[i].WorkingObjects); data.AddFromWorkingColliders(infos[i].Name, infos[i].Colliders); if (writeNoPrefab) { if (hlodDatas.ContainsKey(i) == false) { HLODData newData = new HLODData(); newData.CompressionData = compressionData; hlodDatas.Add(i, newData); } HLODData prefabData = hlodDatas[i]; var spaceNode = infos[i].Target; for (int oi = 0; oi < spaceNode.Objects.Count; ++oi) { if (PrefabUtility.IsAnyPrefabInstanceRoot(spaceNode.Objects[oi]) == false) { prefabData.AddFromGameObject(spaceNode.Objects[oi]); } } } if (onProgress != null) { onProgress((float)i / (float)infos.Count); } } if (extractMaterial) { ExtractMaterial(hlodDatas, filenamePrefix); } Dictionary <int, RootData> rootDatas = new Dictionary <int, RootData>(); foreach (var item in hlodDatas) { string filename = $"{filenamePrefix}_group{item.Key}.hlod"; using (Stream stream = new FileStream(filename, FileMode.Create)) { HLODDataSerializer.Write(stream, item.Value); stream.Close(); } AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate); RootData rootData = AssetDatabase.LoadAssetAtPath <RootData>(filename); m_manager.AddGeneratedResource(rootData); AddAddress(settings, group, rootData); rootDatas.Add(item.Key, rootData); } var addressableController = root.AddComponent <AddressableHLODController>(); for (int i = 0; i < infos.Count; ++i) { var spaceNode = infos[i].Target; var hlodTreeNode = convertedTable[infos[i].Target]; for (int oi = 0; oi < spaceNode.Objects.Count; ++oi) { int highId = -1; GameObject obj = spaceNode.Objects[oi]; if (PrefabUtility.IsPartOfAnyPrefab(obj) == false) { GameObject rootGameObject = null; if (rootDatas.ContainsKey(i)) { rootGameObject = rootDatas[i].GetRootObject(obj.name); } if (rootGameObject != null) { GameObject go = PrefabUtility.InstantiatePrefab(rootGameObject) as GameObject; go.transform.SetParent(obj.transform.parent); go.transform.localPosition = obj.transform.localPosition; go.transform.localRotation = obj.transform.localRotation; go.transform.localScale = obj.transform.localScale; if (m_manager.IsGeneratedResource(obj)) { m_manager.AddGeneratedResource(go); } else { m_manager.AddConvertedPrefabResource(go); } spaceNode.Objects.Add(go); Object.DestroyImmediate(obj); continue; } } var address = GetAddress(spaceNode.Objects[oi]); if (string.IsNullOrEmpty(address) && PrefabUtility.IsAnyPrefabInstanceRoot(spaceNode.Objects[oi])) { AddAddress(settings, group, spaceNode.Objects[oi]); address = GetAddress(spaceNode.Objects[oi]); } if (address != null) { highId = addressableController.AddHighObject(address, spaceNode.Objects[oi]); } else { highId = addressableController.AddHighObject(spaceNode.Objects[oi]); } hlodTreeNode.HighObjectIds.Add(highId); } { if (rootDatas[infos[i].ParentIndex].GetRootObject(infos[i].Name) != null) { string filename = $"{filenamePrefix}_group{infos[i].ParentIndex}.hlod"; int lowId = addressableController.AddLowObject(filename + "[" + infos[i].Name + "]"); hlodTreeNode.LowObjectIds.Add(lowId); } } } var shaderEntriesAdded = new List <AddressableAssetEntry>(); foreach (var shaderGuid in m_shaderGuids) { if (IsExistsInAddressables(shaderGuid) == false) { shaderEntriesAdded.Add(settings.CreateOrMoveEntry(shaderGuid, group, false, false)); } } settings.SetDirty(AddressableAssetSettings.ModificationEvent.EntryMoved, shaderEntriesAdded, true); m_shaderGuids.Clear(); addressableController.Container = container; addressableController.Root = convertedRootNode; addressableController.CullDistance = cullDistance; addressableController.LODDistance = lodDistance; }
private static void BuildAssetBundles() { AddressableAssetSettings.BuildPlayerContent(); }
internal override void Setup(AddressableAssetSettings settings, string tempAssetFolder) { settings.BundleLocalCatalog = true; }
internal static string ErrorCheckBundleSettings(BundledAssetGroupSchema schema, AddressableAssetGroup assetGroup, AddressableAssetSettings settings) { var message = string.Empty; var buildPath = settings.profileSettings.GetValueById(settings.activeProfileId, schema.BuildPath.Id); var loadPath = settings.profileSettings.GetValueById(settings.activeProfileId, schema.LoadPath.Id); var buildLocal = buildPath.Contains("[UnityEngine.AddressableAssets.Addressables.BuildPath]"); var loadLocal = loadPath.Contains("{UnityEngine.AddressableAssets.Addressables.RuntimePath}"); if (buildLocal && !loadLocal) { message = "BuildPath for group '" + assetGroup.Name + "' is set to the dynamic-lookup version of StreamingAssets, but LoadPath is not. \n"; } else if (!buildLocal && loadLocal) { message = "LoadPath for group " + assetGroup.Name + " is set to the dynamic-lookup version of StreamingAssets, but BuildPath is not. These paths must both use the dynamic-lookup, or both not use it. \n"; } if (!string.IsNullOrEmpty(message)) { message += "BuildPath: '" + buildPath + "'\n"; message += "LoadPath: '" + loadPath + "'"; } return(message); }
private static void BuildPlayerHandler(BuildPlayerOptions options) { AddressableAssetSettings.BuildPlayerContent(); BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options); }
void OnCleanAddressables(object builder) { AddressableAssetSettings.CleanPlayerContent(builder as IDataBuilder); }
public void OnPreprocessBuild(BuildTarget target, string path) { AddressableAssetSettings.CleanPlayerContent(AddressableAssetSettingsDefaultObject.Settings.ActivePlayerDataBuilder); AddressableAssetSettings.BuildPlayerContent(); var Gamedata = AssetDatabase.LoadAssetAtPath <GameObject>( "Assets/Prefabs/SceneConstruction/NestedManagers/GameData.prefab"); if (Gamedata.GetComponent <GameData>().DevBuild == false) { return; } EditorUtility.SetDirty(Gamedata); AssetDatabase.SaveAssets(); var paths = GetCataloguePath(); foreach (var addpath in paths) { var flip = new FileInfo(addpath); var towork = flip.Directory; // var endpath = Application.dataPath.Remove(Application.dataPath.IndexOf("/Assets")); // endpath = endpath + towork; var DD = towork; var newendpath = Application.streamingAssetsPath + "/AddressableCatalogues/" + flip.Directory.Parent.Name + "/"; var newDD = new DirectoryInfo(newendpath); Directory.CreateDirectory(newendpath); CopyFilesRecursively(DD, newDD); //Logger.Log(newendpath); var Files = System.IO.Directory.GetFiles(flip.Directory.ToString()); string FoundFile = ""; foreach (var File in Files) { //Logger.Log(File); if (File.EndsWith(".json")) { if (FoundFile != "") { Logger.LogError("two catalogues present please only ensure one", Category.Addressables); } FoundFile = File; } } if (File.Exists(newendpath + Path.GetFileName(FoundFile))) { File.Delete(newendpath + Path.GetFileName(FoundFile)); } if (File.Exists(newendpath + Path.GetFileName(FoundFile).Replace(".json", ".hash"))) { File.Delete(newendpath + Path.GetFileName(FoundFile).Replace(".json", ".hash")); } var Stringtime = DateTime.Now.Ticks.ToString(); System.IO.File.Copy(FoundFile, newendpath + Stringtime + ".json"); System.IO.File.Copy(FoundFile.Replace(".json", ".hash"), (newendpath + Stringtime + ".hash")); JObject o1 = JObject.Parse(File.ReadAllText((@newendpath + Stringtime + ".json".Replace("/", @"\")))); var IDs = (JArray)o1["m_InternalIds"]; for (int i = 0; i < IDs.Count; i++) { var newID = IDs[i].ToString(); newID = newID.Replace("AddressablePackingProjects/" + flip.Directory.Parent.Name + "/ServerData/", "unitystation_Data/StreamingAssets/AddressableCatalogues/" + flip.Directory.Parent.Name + "/"); newID = newID.Replace(@"AddressablePackingProjects\" + flip.Directory.Parent.Name + @"\ServerData\", "unitystation_Data/StreamingAssets/AddressableCatalogues/" + flip.Directory.Parent.Name + "/"); //Assets < Editor, build > unitystation_Data //Check cache in app data if changes aren't applying IDs[i] = newID; } File.WriteAllText(newendpath + Stringtime + ".json", Newtonsoft.Json.JsonConvert.SerializeObject(o1, Newtonsoft.Json.Formatting.None)); } // var ff = new Dictionary<string,string>(); // var nice = ff["STOP"].Length; }
void OnBuildPlayerData() { AddressableAssetSettings.BuildPlayerContent(); }
internal List <AnalyzeResult> CalculateBuiltInResourceDependenciesToBundleDependencies(AddressableAssetSettings settings, string[] builtInResourcesPaths) { List <AnalyzeResult> results = new List <AnalyzeResult>(); if (!BuildUtility.CheckModifiedScenesAndAskToSave()) { Debug.LogError("Cannot run Analyze with unsaved scenes"); results.Add(new AnalyzeResult { resultName = ruleName + "Cannot run Analyze with unsaved scenes" }); return(results); } m_addressableAssets = (from aaGroup in settings.groups where aaGroup != null from entry in aaGroup.entries select new GUID(entry.guid)).ToList(); BuiltInResourcesToDependenciesMap(builtInResourcesPaths); CalculateInputDefinitions(settings); var context = GetBuildContext(settings); ReturnCode exitCode = RefreshBuild(context); if (exitCode < ReturnCode.Success) { Debug.LogError("Analyze build failed. " + exitCode); results.Add(new AnalyzeResult { resultName = ruleName + "Analyze build failed. " + exitCode }); return(results); } IntersectResourcesDependenciesWithBundleDependencies(GetAllBundleDependencies()); ConvertBundleNamesToGroupNames(context); results = (from resource in m_resourcesToDependencies.Keys from dependency in m_resourcesToDependencies[resource] let assetPath = AssetDatabase.GUIDToAssetPath(dependency.ToString()) let files = m_extractData.WriteData.FileToObjects.Keys from file in files where m_extractData.WriteData.FileToObjects[file].Any(oid => oid.guid == dependency) where m_extractData.WriteData.FileToBundle.ContainsKey(file) let bundle = m_extractData.WriteData.FileToBundle[file] select new AnalyzeResult { resultName = resource + kDelimiter + bundle + kDelimiter + assetPath, severity = MessageType.Warning }).ToList(); if (results.Count == 0) { results.Add(new AnalyzeResult { resultName = ruleName + " - No issues found." }); } return(results); }
public ProfileRenameVariablePopup(Rect fieldRect, AddressableAssetProfileSettings.ProfileIdData profileVariable, AddressableAssetSettings settings) { m_WindowRect = fieldRect; m_ProfileVariable = profileVariable; m_Settings = settings; m_NewName = m_ProfileVariable.ProfileName; UnityEngine.GUI.enabled = true; }
static AddressableAssetGroup GetGroupFromBundle(string bundleName, Dictionary <string, string> bundleToAssetGroupGUID, AddressableAssetSettings settings) { if (!bundleToAssetGroupGUID.TryGetValue(bundleName, out string groupGuid)) { return(settings.DefaultGroup); } return(settings.FindGroup(g => g != null && g.Guid == groupGuid)); }
TResult DoBuild <TResult>(AddressablesDataBuilderInput builderInput, AddressableAssetSettings aaSettings, AddressableAssetsBuildContext aaContext) where TResult : IDataBuilderResult { if (m_AllBundleInputDefinitions.Count > 0) { if (!BuildUtility.CheckModifiedScenesAndAskToSave()) { 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(ResourceManagerRuntimeData.kCatalogAddress); contentCatalog.SetData(aaContext.locations, aaContext.Settings.OptimizeCatalogSize); 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); }
internal static void MoveAssetsFromResources(Dictionary <string, string> guidToNewPath, AddressableAssetGroup targetParent, AddressableAssetSettings settings) { if (guidToNewPath == null) { return; } var entries = new List <AddressableAssetEntry>(); AssetDatabase.StartAssetEditing(); foreach (var item in guidToNewPath) { var dirInfo = new FileInfo(item.Value).Directory; if (dirInfo != null && !dirInfo.Exists) { dirInfo.Create(); AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); AssetDatabase.StartAssetEditing(); } var oldPath = AssetDatabase.GUIDToAssetPath(item.Key); var errorStr = AssetDatabase.MoveAsset(oldPath, item.Value); if (!string.IsNullOrEmpty(errorStr)) { DebugUtility.LogError(LoggerTags.Engine, "Error moving asset:{0} ", errorStr); } else { AddressableAssetEntry e = settings.FindAssetEntry(item.Key); if (e != null) { e.IsInResources = false; } var newEntry = settings.CreateOrMoveEntry(item.Key, targetParent, false, false); var index = oldPath.ToLower().LastIndexOf("resources/"); if (index >= 0) { var newAddress = Path.GetFileNameWithoutExtension(oldPath.Substring(index + 10)); if (!string.IsNullOrEmpty(newAddress)) { newEntry.address = newAddress; } } entries.Add(newEntry); } } AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); settings.SetDirty(AddressableAssetSettings.ModificationEvent.EntryMoved, entries, true, true); }
static AddressableAssetGroup CreateAssetGroup(AddressableAssetSettings settings, string groupName) { return(settings.CreateGroup(groupName, false, false, false, null, typeof(ContentUpdateGroupSchema), typeof(BundledAssetGroupSchema))); }
public static IEnumerator PackageWorlds(int packageMode, int releaseChannel, bool allWorlds, bool allTargets, bool force = false, bool linuxOnly = false) { uploadPossible = false; packagingInProgress = true; packagingSuccessful = false; try { string[] worldsToBuild = allWorlds ? GetWorldPaths() : GetWorldsToBuild(packageMode); if (worldsToBuild.Length == 0) { yield break; } string resultFolder = Application.dataPath + "/../traVRsal/"; BuildTarget mainTarget = linuxOnly || Application.platform == RuntimePlatform.LinuxEditor ? BuildTarget.StandaloneLinux64 : BuildTarget.StandaloneWindows64; CreateLockFile(); ConvertTileMaps(); CreateAddressableSettings(!allTargets, releaseChannel); EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC; EditorUserBuildSettings.selectedStandaloneTarget = mainTarget; PlayerSettings.SetScriptingBackend(BuildTargetGroup.Standalone, ScriptingImplementation.Mono2x); // Linux can only be built with Mono on Windows AddressableAssetSettings.CleanPlayerContent(); AssetDatabase.SaveAssets(); if (Directory.Exists(GetServerDataPath()) && (packageMode == 0 || allWorlds)) { Directory.Delete(GetServerDataPath(), true); } // set build targets List <Tuple <BuildTargetGroup, BuildTarget> > targets = new List <Tuple <BuildTargetGroup, BuildTarget> >(); if (allTargets) { targets.Add(new Tuple <BuildTargetGroup, BuildTarget>(BuildTargetGroup.Android, BuildTarget.Android)); // set windows/linux last so that we can continue with editor iterations normally right afterwards if (Application.platform == RuntimePlatform.LinuxEditor) { targets.Add(new Tuple <BuildTargetGroup, BuildTarget>(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64)); targets.Add(new Tuple <BuildTargetGroup, BuildTarget>(BuildTargetGroup.Standalone, BuildTarget.StandaloneLinux64)); } else { if (linuxSupport) { targets.Add(new Tuple <BuildTargetGroup, BuildTarget>(BuildTargetGroup.Standalone, BuildTarget.StandaloneLinux64)); } targets.Add(new Tuple <BuildTargetGroup, BuildTarget>(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64)); } } else { targets.Add(new Tuple <BuildTargetGroup, BuildTarget>(BuildTargetGroup.Standalone, mainTarget)); } // update world content foreach (string dir in worldsToBuild) { string worldName = Path.GetFileName(dir); if (!UpdateWorldData(worldName)) { yield break; } } // iterate over all supported platforms foreach (Tuple <BuildTargetGroup, BuildTarget> target in targets) { EditorUserBuildSettings.SwitchActiveBuildTarget(target.Item1, target.Item2); // build each world individually AddressableAssetSettings settings = AddressableAssetSettingsDefaultObject.GetSettings(true); foreach (string dir in worldsToBuild) { string worldName = Path.GetFileName(dir); string serverDir = GetServerDataPath() + "/Worlds/" + Path.GetFileName(dir); if (!allTargets && Directory.Exists(resultFolder + worldName)) { Directory.Delete(resultFolder + worldName, true); } if (packageMode == 1 && !allWorlds && Directory.Exists(serverDir)) { Directory.Delete(serverDir, true); } settings.activeProfileId = settings.profileSettings.GetProfileId(worldName); settings.groups.ForEach(group => { if (group.ReadOnly) { return; } group.GetSchema <BundledAssetGroupSchema>().IncludeInBuild = group.name == worldName; // default group ensures there is no accidental local default group resulting in local paths being baked into addressable for shaders if (group.name == worldName && group.CanBeSetAsDefault()) { settings.DefaultGroup = group; } }); BundledAssetGroupSchema schema = settings.groups.First(group => @group.name == worldName).GetSchema <BundledAssetGroupSchema>(); settings.RemoteCatalogBuildPath = schema.BuildPath; settings.RemoteCatalogLoadPath = schema.LoadPath; settings.ShaderBundleCustomNaming = worldName; AddressableAssetSettings.BuildPlayerContent(); } } CreateAddressableSettings(!allTargets, releaseChannel); // do again to have clean build state, as some settings were messed with while building RenameCatalogs(); packagingSuccessful = true; } catch (Exception e) { packagingInProgress = false; EditorUtility.DisplayDialog("Error", $"Packaging could not be completed. Error: {e.Message}", "Close"); yield break; } if (dirWatcher != null) { dirWatcher.ClearAffected(); // only do at end, since during build might cause false positives } else { CreateDirWatcher(); // can happen after initial project creation } RemoveLockFile(); packagingInProgress = false; Debug.Log("Packaging completed successfully."); }
internal virtual void Setup(AddressableAssetSettings settings, string tempAssetFolder) { }
private static void CreateAddressableSettings(bool localMode, int releaseChannel) { AddressableAssetSettings settings = AddressableAssetSettingsDefaultObject.GetSettings(true); settings.ActivePlayModeDataBuilderIndex = localMode ? 0 : 2; settings.BuildRemoteCatalog = true; settings.DisableCatalogUpdateOnStartup = true; settings.ContiguousBundles = true; settings.IgnoreUnsupportedFilesInBuild = true; settings.ShaderBundleNaming = ShaderBundleNaming.Custom; // don't include built-in data, causes shader issues settings.groups.ForEach(g => { PlayerDataGroupSchema schema = g.GetSchema <PlayerDataGroupSchema>(); if (schema != null) { schema.IncludeBuildSettingsScenes = false; schema.IncludeResourcesFolders = false; } }); // setup profiles AddressableAssetProfileSettings profile = settings.profileSettings; // activate and (re)group assets foreach (string dir in GetWorldPaths()) { string worldName = Path.GetFileName(dir); bool isBase = worldName == "Base"; // create one profile per world string profileId = profile.GetProfileId(worldName); if (string.IsNullOrEmpty(profileId)) { profileId = profile.AddProfile(worldName, settings.activeProfileId); } string guid = AssetDatabase.AssetPathToGUID($"Assets/Worlds/{worldName}"); // create group if non-existent AddressableAssetGroup group = settings.groups.FirstOrDefault(g => g.name == worldName); if (group == null) { group = CreateAssetGroup <BundledAssetGroupSchema>(settings, worldName); } if (group.CanBeSetAsDefault()) { settings.DefaultGroup = group; // default group ensures there is no accidental local default group resulting in local paths being baked into addressable for shaders } // set correct path AddressableAssetEntry entry = settings.CreateOrMoveEntry(guid, group); entry.SetAddress($"Worlds/{worldName}"); // set variables string localRoot = Application.dataPath + $"/../traVRsal/{worldName}/[BuildTarget]"; string remoteTarget = null; switch (releaseChannel) { case 0: remoteTarget = AWSUtil.S3CDNRoot_Live; break; case 1: remoteTarget = AWSUtil.S3CDNRoot_Beta; break; case 2: remoteTarget = AWSUtil.S3CDNRoot_Alpha; break; } profile.SetValue(profileId, AddressableAssetSettings.kLocalBuildPath, localRoot); profile.SetValue(profileId, AddressableAssetSettings.kLocalLoadPath, localRoot); profile.SetValue(profileId, AddressableAssetSettings.kRemoteBuildPath, $"ServerData/Worlds/{worldName}/[BuildTarget]"); profile.SetValue(profileId, AddressableAssetSettings.kRemoteLoadPath, $"{remoteTarget}Worlds/{worldName}/[BuildTarget]"); // ensure correct group settings BundledAssetGroupSchema groupSchema = group.GetSchema <BundledAssetGroupSchema>(); groupSchema.UseAssetBundleCache = true; groupSchema.UseAssetBundleCrc = false; groupSchema.IncludeInBuild = isBase; groupSchema.RetryCount = 3; groupSchema.BundleNaming = BundledAssetGroupSchema.BundleNamingStyle.NoHash; // hash to disambiguate identically named files yields same error messages, e.g. standard shaders groupSchema.BundleMode = BundledAssetGroupSchema.BundlePackingMode.PackTogether; groupSchema.Compression = BundledAssetGroupSchema.BundleCompressionMode.LZ4; groupSchema.BuildPath.SetVariableByName(settings, localMode ? AddressableAssetSettings.kLocalBuildPath : AddressableAssetSettings.kRemoteBuildPath); groupSchema.LoadPath.SetVariableByName(settings, localMode ? AddressableAssetSettings.kLocalLoadPath : AddressableAssetSettings.kRemoteLoadPath); } }
internal static void GatherExplicitModifiedEntries(AddressableAssetSettings settings, ref Dictionary <AddressableAssetEntry, List <AddressableAssetEntry> > dependencyMap, AddressablesContentState cacheData) { List <string> noBundledAssetGroupSchema = new List <string>(); List <string> noStaticContent = new List <string>(); var allEntries = new List <AddressableAssetEntry>(); settings.GetAllAssets(allEntries, false, g => { if (g == null) { return(false); } if (!g.HasSchema <BundledAssetGroupSchema>()) { noBundledAssetGroupSchema.Add(g.Name); return(false); } if (!g.HasSchema <ContentUpdateGroupSchema>()) { noStaticContent.Add(g.Name); return(false); } if (!g.GetSchema <ContentUpdateGroupSchema>().StaticContent) { noStaticContent.Add(g.Name); return(false); } return(true); }); StringBuilder builder = new StringBuilder(); builder.AppendFormat("Skipping Prepare for Content Update on {0} group(s):\n\n", noBundledAssetGroupSchema.Count + noStaticContent.Count); AddInvalidGroupsToLogMessage(builder, noBundledAssetGroupSchema, "Group Did Not Contain BundledAssetGroupSchema"); AddInvalidGroupsToLogMessage(builder, noStaticContent, "Static Content Not Enabled In Schemas"); Debug.Log(builder.ToString()); var entryToCacheInfo = new Dictionary <string, CachedAssetState>(); foreach (var cacheInfo in cacheData.cachedInfos) { if (cacheInfo != null) { entryToCacheInfo[cacheInfo.asset.guid.ToString()] = cacheInfo; } } var modifiedEntries = new List <AddressableAssetEntry>(); foreach (var entry in allEntries) { CachedAssetState cachedInfo; if (!entryToCacheInfo.TryGetValue(entry.guid, out cachedInfo) || HasAssetOrDependencyChanged(cachedInfo)) { modifiedEntries.Add(entry); } } AddAllDependentScenesFromModifiedEntries(modifiedEntries); foreach (var entry in modifiedEntries) { if (!dependencyMap.ContainsKey(entry)) { dependencyMap.Add(entry, new List <AddressableAssetEntry>()); } } }
public override List <AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings) { ClearAnalysis(); return(CheckForDuplicateDependencies(settings)); }
public static string ValueGUI(Rect rect, AddressableAssetSettings settings, string label, string currentId, ref bool wasChanged) { string result = currentId; if (settings == null) { return(result); } var displayNames = settings.profileSettings.GetVariableNames(); AddressableAssetProfileSettings.ProfileIdData data = settings.profileSettings.GetProfileDataById(currentId); bool custom = data == null && currentId != "—"; int currentIndex = displayNames.Count; string toolTip = string.Empty; if (currentId == "—") { currentIndex = -1; toolTip = "—"; result = "—"; } else { if (!custom) { currentIndex = displayNames.IndexOf(data.ProfileName); toolTip = data.Evaluate(settings.profileSettings, settings.activeProfileId); } } displayNames.Add(AddressableAssetProfileSettings.customEntryString); var labelContent = new GUIContent(label); var size = EditorStyles.popup.CalcSize(labelContent); var topRect = new Rect(rect.x, rect.y, rect.width, size.y); EditorGUI.BeginChangeCheck(); var newIndex = EditorGUI.Popup(topRect, label, currentIndex, displayNames.ToArray()); wasChanged = EditorGUI.EndChangeCheck(); if (newIndex != -1 && newIndex != currentIndex) { if (displayNames[newIndex] == AddressableAssetProfileSettings.customEntryString) { custom = true; result = AddressableAssetProfileSettings.undefinedEntryValue; } else { data = settings.profileSettings.GetProfileDataByName(displayNames[newIndex]); if (data != null) { result = data.Id; } } } var bottomRect = new Rect(rect.x, rect.y + size.y + EditorGUIUtility.standardVerticalSpacing, rect.width, rect.height - (size.y + EditorGUIUtility.standardVerticalSpacing)); if (custom) { result = EditorGUI.TextField(bottomRect, " ", result); } else if (!string.IsNullOrEmpty(toolTip)) { GUIStyle pathBox = new GUIStyle(EditorStyles.miniLabel); pathBox.wordWrap = true; EditorGUI.LabelField(bottomRect, " ", toolTip, pathBox); } return(result); }
public static void BuildAndroidWithBundle() { AddressableAssetSettings.BuildPlayerContent(); BuildAndroid(); }