protected virtual string ConstructAssetBundleName(AddressableAssetGroup assetGroup, BundledAssetGroupSchema schema, BundleDetails info, string assetBundleName)
        {
            string groupName = assetGroup.Name.Replace(" ", "").Replace('\\', '/').Replace("//", "/").ToLower();

            assetBundleName = groupName + "_" + assetBundleName;
            return(BuildUtility.GetNameWithHashNaming(schema.BundleNaming, info.Hash.ToString(), assetBundleName));
        }
Beispiel #2
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty sceneAssetProperty = property.FindPropertyRelative("sceneAsset");
            SerializedProperty scenePathProperty  = property.FindPropertyRelative("scenePath");

            label = EditorGUI.BeginProperty(position, label, property);
            EditorGUI.BeginChangeCheck();

            Object selectedObject = EditorGUI.ObjectField(position, label, sceneAssetProperty.objectReferenceValue, typeof(SceneAsset), false);

            BuildUtility.BuildScene buildScene = BuildUtility.GetBuildScene(selectedObject);

            if (EditorGUI.EndChangeCheck())
            {
                sceneAssetProperty.objectReferenceValue = selectedObject;

                // If the set scene was invalid, reset the path.
                if (buildScene.scene == null)
                {
                    scenePathProperty.stringValue = "";
                }
            }

            EditorGUI.EndProperty();
        }
Beispiel #3
0
        internal static List <TargetInfo> GatherTargetInfos(Object[] targets, AddressableAssetSettings aaSettings)
        {
            var targetInfos = new List <TargetInfo>();
            AddressableAssetEntry entry;

            foreach (var t in targets)
            {
                if (AddressableAssetUtility.TryGetPathAndGUIDFromTarget(t, out var path, out var guid))
                {
                    var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(path);
                    // Is asset
                    if (mainAssetType != null && !BuildUtility.IsEditorAssembly(mainAssetType.Assembly))
                    {
                        bool isMainAsset = t is AssetImporter || AssetDatabase.IsMainAsset(t);
                        var  info        = new TargetInfo()
                        {
                            TargetObject = t, Guid = guid, Path = path, IsMainAsset = isMainAsset
                        };

                        if (aaSettings != null)
                        {
                            entry = aaSettings.FindAssetEntry(guid, true);
                            if (entry != null)
                            {
                                info.MainAssetEntry = entry;
                            }
                        }

                        targetInfos.Add(info);
                    }
                }
            }

            return(targetInfos);
        }
Beispiel #4
0
        internal static bool IsPathValidForEntry(string path)
        {
            if (String.IsNullOrEmpty(path))
            {
                return(false);
            }
            path = path.ToLower();
            if (path == CommonStrings.UnityEditorResourcePath ||
                path == CommonStrings.UnityDefaultResourcePath ||
                path == CommonStrings.UnityBuiltInExtraPath)
            {
                return(false);
            }
            var ext = Path.GetExtension(path);

            if (ext == ".cs" || ext == ".js" || ext == ".boo" || ext == ".exe" || ext == ".dll")
            {
                return(false);
            }
            var t = AssetDatabase.GetMainAssetTypeAtPath(path);

            if (t != null && BuildUtility.IsEditorAssembly(t.Assembly))
            {
                return(false);
            }
            return(true);
        }
    public static void Build()
    {
        // Create a 'Builds' folder in the root project folder to export the build to.
        if (!Directory.Exists("Builds"))
        {
            Directory.CreateDirectory("Builds");
        }

        // Call PreprocessBuild before starting the build to remove all nested prefab data from the project.
        BuildUtility.PreprocessBuild();
        {
            // Create a build.
            BuildPipeline.BuildPlayer(
                new string[]
            {
                "Assets/test.unity"
            },
                "builds/build.exe",
                BuildTarget.StandaloneWindows,
                BuildOptions.None);

            // Switch to Android and create another build
            BuildPipeline.BuildPlayer(
                new string[]
            {
                "Assets/test.unity"
            },
                "builds/build.apk",
                BuildTarget.Android,
                BuildOptions.None);
        }
        // Call PostprocessBuild after building to restore all nested prefab data.
        BuildUtility.PostprocessBuild();
    }
Beispiel #6
0
        internal static bool CheckForEditorAssembly(ref Type t, string internalId, bool warnIfStripped)
        {
            if (t == null)
            {
                return(false);
            }
            if (t.Assembly.IsDefined(typeof(AssemblyIsEditorAssembly), true) || BuildUtility.IsEditorAssembly(t.Assembly))
            {
                if (t == typeof(UnityEditor.Animations.AnimatorController))
                {
                    t = typeof(RuntimeAnimatorController);
                    return(true);
                }
                if (t.FullName == "UnityEditor.Audio.AudioMixerController")
                {
                    t = typeof(UnityEngine.Audio.AudioMixer);
                    return(true);
                }

                if (t.FullName == "UnityEditor.Audio.AudioMixerGroupController")
                {
                    t = typeof(UnityEngine.Audio.AudioMixerGroup);
                    return(true);
                }
                if (warnIfStripped)
                {
                    Debug.LogWarningFormat("Type {0} is in editor assembly {1}.  Asset location with internal id {2} will be stripped.", t.Name, t.Assembly.FullName, internalId);
                }
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Check for duplicates among the dependencies and build implicit duplicates
        /// </summary>
        /// <param name="settings">The current Addressables settings object</param>
        /// <returns>List of results from analysis</returns>
        protected List <AnalyzeResult> CheckForDuplicateDependencies(AddressableAssetSettings settings)
        {
            if (!BuildUtility.CheckModifiedScenesAndAskToSave())
            {
                Debug.LogError("Cannot run Analyze with unsaved scenes");
                m_Results.Add(new AnalyzeResult {
                    resultName = ruleName + "Cannot run Analyze with unsaved scenes"
                });
                return(m_Results);
            }

            CalculateInputDefinitions(settings);

            if (m_AllBundleInputDefs.Count > 0)
            {
                var        context  = GetBuildContext(settings);
                ReturnCode exitCode = RefreshBuild(context);
                if (exitCode < ReturnCode.Success)
                {
                    Debug.LogError("Analyze build failed. " + exitCode);
                    m_Results.Add(new AnalyzeResult {
                        resultName = ruleName + "Analyze build failed. " + exitCode
                    });
                    return(m_Results);
                }

                var implicitGuids    = GetImplicitGuidToFilesMap();
                var checkDupeResults = CalculateDuplicates(implicitGuids, context);
                BuildImplicitDuplicatedAssetsSet(checkDupeResults);
            }

            RefreshDisplay();
            return(m_Results);
        }
Beispiel #8
0
        internal List<AnalyzeResult> CalculateBuiltInResourceDependenciesToBundleDependecies(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;
            }

            IntersectResourcesDepedenciesWithBundleDependencies(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;
        }
        private void DoRegenerateSync()
        {
            foreach (var configuration in ProviderResolver.GetConfigurations())
            {
                var syncResult = GetSyncResult(configuration);

                if (syncResult.AreTemplatesSynchronized)
                {
                    return;
                }

                if (!syncResult.AreTemplatesSynchronized)
                {
                    foreach (var template in syncResult)
                    {
                        if (!template.IsSynchronized)
                        {
                            Log.Warn("Synthesis template desynchronization ({0}): {1}".FormatWith(configuration.Name, template), this);
                        }
                    }
                }

                string projectPathValue = StartupRegenerateProjectPath;

                if (StartupRegenerateProjectPath == "auto" || string.IsNullOrWhiteSpace(StartupRegenerateProjectPath))
                {
                    projectPathValue = ResolveAutoProjectPath(configuration.GeneratorParametersProvider.CreateParameters(configuration.Name));

                    if (projectPathValue == null)
                    {
                        throw new InvalidOperationException("Unable to automatically find a valid project file to build. I looked at sibling and parent folders to the concrete file output path for *proj.");
                    }
                }
                else
                {
                    projectPathValue = ConfigurationUtility.ResolveConfigurationPath(projectPathValue);
                }

                if (!File.Exists(projectPathValue))
                {
                    throw new InvalidOperationException("The auto-rebuild project file \"" + projectPathValue + "\" did not exist.");
                }

                var metadata = configuration.CreateMetadataGenerator().GenerateMetadata();

                configuration.CreateCodeGenerator().Generate(metadata);

                var outputLogPath = Path.GetDirectoryName(projectPathValue) + Path.DirectorySeparatorChar + "synthesis-autobuild.log";

                if (!BuildUtility.BuildProject(projectPathValue, "Release", outputLogPath))
                {
                    Log.Error("Synthesis automatic project build on " + projectPathValue + " failed! Review the build log at " + outputLogPath + " to find out what happened.", this);
                }

                Log.Info("Synthesis detected templates were not synchronized for {0} and attempted to automatically rebuild {1} to correct the problem.".FormatWith(configuration.Name, projectPathValue), this);
            }
        }
        public void GetNameWithHashNaming_ReturnsNoChangeIfNoHash()
        {
            string source   = "x/y.bundle";
            string hash     = "123abc";
            string expected = "x/y.bundle";

            var actual = BuildUtility.GetNameWithHashNaming(BundledAssetGroupSchema.BundleNamingStyle.NoHash, hash, source);

            Assert.AreEqual(expected, actual);
        }
        public void GetNameWithHashNaming_CanReplaceFileNameWithHash()
        {
            string source   = "x/y.bundle";
            string hash     = "123abc";
            string expected = "123abc.bundle";

            var actual = BuildUtility.GetNameWithHashNaming(BundledAssetGroupSchema.BundleNamingStyle.OnlyHash, hash, source);

            Assert.AreEqual(expected, actual);
        }
        public void GetNameWithHashNaming_CanReplaceFileNameWithFileNameHash()
        {
            string source   = "x/y.bundle";
            string hash     = HashingMethods.Calculate(source).ToString();
            string expected = hash + ".bundle";

            var actual = BuildUtility.GetNameWithHashNaming(BundledAssetGroupSchema.BundleNamingStyle.FileNameHash, hash, source);

            Assert.AreEqual(expected, actual);
        }
        public static void BuildVersionModify()
        {
            BuildVersionWindow.Init((buildData) =>
            {
                ModifyBuildVersion(buildData);

                string gradlePath = Path.Combine(Application.dataPath, "../JenkinsScripts/AndroidGradleStuff/launcher/build.gradle");
                BuildUtility.HandleGradleVersion(gradlePath, buildData);
            });
        }
Beispiel #14
0
        private void DoRegenerateSync(XmlNode config)
        {
            var syncResult = GetSyncResult();

            if (syncResult.AreTemplatesSynchronized)
            {
                return;
            }

            if (!syncResult.AreTemplatesSynchronized)
            {
                foreach (var template in syncResult)
                {
                    if (!template.IsSynchronized)
                    {
                        Log.Warn("Synthesis template desynchronization: " + template, this);
                    }
                }
            }

            var projectPathNode = config.SelectSingleNode("setting[@name='StartupRegenerateProjectPath']");

            if (projectPathNode == null || projectPathNode.Attributes["value"] == null)
            {
                throw new InvalidOperationException("The StartupRegenerateProjectPath setting must be specified when Synthesis Sync StartupCheckMode is set to Regenerate");
            }

            var projectPathValue = projectPathNode.Attributes["value"].InnerText;

            if (projectPathValue == "auto")
            {
                projectPathValue = ResolveAutoProjectPath();

                if (projectPathValue == null)
                {
                    throw new InvalidOperationException("Unable to automatically find a valid project file to build. I looked at sibling and parent folders to the concrete file output path for *proj.");
                }
            }

            if (!File.Exists(projectPathValue))
            {
                throw new InvalidOperationException("The auto-rebuild project file \"" + projectPathValue + "\" did not exist.");
            }

            ProviderResolver.CreateGenerator().GenerateToDisk();

            var outputLogPath = Path.GetDirectoryName(projectPathValue) + Path.DirectorySeparatorChar + "synthesis-autobuild.log";

            if (!BuildUtility.BuildProject(projectPathValue, "Release", outputLogPath))
            {
                Log.Error("Synthesis automatic project build on " + projectPathValue + " failed! Review the build log at " + outputLogPath + " to find out what happened.", this);
            }

            Log.Info("Synthesis detected templates were not synchronized and attempted to automatically rebuild " + projectPathValue + " to correct the problem.", this);
        }
Beispiel #15
0
        static void PostProcessBundles(AddressableAssetGroup assetGroup, List <string> bundles, IBundleBuildResults buildResult, IWriteData writeData, ResourceManagerRuntimeData runtimeData, List <ContentCatalogDataEntry> locations, FileRegistry registry)
        {
            var schema = assetGroup.GetSchema <BundledAssetGroupSchema>();

            if (schema == null)
            {
                return;
            }

            var path = schema.BuildPath.GetValue(assetGroup.Settings);

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            foreach (var originalBundleName in bundles)
            {
                var newBundleName = originalBundleName;
                var info          = buildResult.BundleInfos[newBundleName];
                ContentCatalogDataEntry dataEntry = locations.FirstOrDefault(s => newBundleName == (string)s.Keys[0]);
                if (dataEntry != null)
                {
                    var requestOptions = new AssetBundleRequestOptions
                    {
                        Crc             = schema.UseAssetBundleCrc ? info.Crc : 0,
                        Hash            = schema.UseAssetBundleCache ? info.Hash.ToString() : "",
                        ChunkedTransfer = schema.ChunkedTransfer,
                        RedirectLimit   = schema.RedirectLimit,
                        RetryCount      = schema.RetryCount,
                        Timeout         = schema.Timeout,
                        BundleName      = Path.GetFileName(info.FileName),
                        BundleSize      = GetFileSize(info.FileName)
                    };
                    dataEntry.Data = requestOptions;

                    dataEntry.InternalId = BuildUtility.GetNameWithHashNaming(schema.BundleNaming, info.Hash.ToString(), dataEntry.InternalId);
                    newBundleName        = BuildUtility.GetNameWithHashNaming(schema.BundleNaming, info.Hash.ToString(), newBundleName);
                }
                else
                {
                    Debug.LogWarningFormat("Unable to find ContentCatalogDataEntry for bundle {0}.", newBundleName);
                }

                var targetPath = Path.Combine(path, newBundleName);
                if (!Directory.Exists(Path.GetDirectoryName(targetPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                }
                File.Copy(Path.Combine(assetGroup.Settings.buildSettings.bundleBuildPath, originalBundleName), targetPath, true);
                registry.AddFile(targetPath);
            }
        }
Beispiel #16
0
        List <AnalyzeResult> CheckForDuplicateDependencies(AddressableAssetSettings settings)
        {
            var 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);
            }

            CalculateInputDefinitions(settings);

            if (m_allBundleInputDefs.Count > 0)
            {
                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);
                }

                var implicitGuids    = GetImplicitGuidToFilesMap();
                var checkDupeResults = CalculateDuplicates(implicitGuids, context);
                BuildImplicitDuplicatedAssetsSet(checkDupeResults);

                results = (from issueGroup in m_allIssues
                           from bundle in issueGroup.Value
                           from item in bundle.Value
                           select new AnalyzeResult
                {
                    resultName = ruleName + kDelimiter +
                                 issueGroup.Key + kDelimiter +
                                 ConvertBundleName(bundle.Key, issueGroup.Key) + kDelimiter +
                                 item,
                    severity = MessageType.Warning
                }).ToList();
            }

            if (results.Count == 0)
            {
                results.Add(noErrors);
            }

            return(results);
        }
        private void PostBuildAndroid(BuildType type, string path)
        {
            if (EditorUserBuildSettings.exportAsGoogleAndroidProject)
            {
                Debug.Log("ExportAsGooleAndroidProject is switched on. Running Android Greadle PostProcess.");

                // Patch the Perforce ridiculuseness
                // handle unityLibrary AndroidManifest.xml
                BuildUtility.HandleAndroidXml(path);
                // Patch the Perforce ridiculuseness
                string gradlePath = Path.Combine(Application.dataPath, "../JenkinsScripts/AndroidGradleStuff");
                // handle gradle version name
                if (type == BuildType.Development)
                {
                    string           versionPath = Path.Combine(Application.dataPath, "Misc/buildVersion.json");
                    BuildVersionData data        = null;
                    using (StreamReader sr = new StreamReader(versionPath))
                    {
                        string versionData = sr.ReadToEnd();
                        data = JsonUtility.FromJson <BuildVersionData>(versionData);
                    }
                    if (data == null)
                    {
                        return;
                    }
                    BuildUtility.HandleGradleVersion(Path.Combine(gradlePath, "launcher/build.gradle"), data);
                }

                FileUtility.CopyDirectoryFiles(new DirectoryInfo(gradlePath), new DirectoryInfo(path), true, true);
                string androidPath = Path.Combine(Application.dataPath, "../Tools/Android/Builds");
                FileUtility.CopyDirectoryFiles(new DirectoryInfo(androidPath), new DirectoryInfo(path), true, true);

                string gradleBuildType = "Debug";
                if (type == BuildType.Preproduction || type == BuildType.Production)
                {
                    gradleBuildType = "Release";
                }
                try
                {
                    // Run APK support
                    BuildUtility.RunGradleProcess(path, gradleBuildType);
                    // Bundle support
                    BuildUtility.RunGradleProcess(path, gradleBuildType, "bundle");
                }
                catch (System.Exception error)
                {
                    Debug.LogError("Android build python process failed. msg : " + error.Message);
                }
            }
        }
Beispiel #18
0
        public override List <AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings)
        {
            ClearAnalysis();

            if (!BuildUtility.CheckModifiedScenesAndAskToSave())
            {
                Debug.LogError("Cannot run Analyze with unsaved scenes");
                m_Results.Add(new AnalyzeResult {
                    resultName = ruleName + "Cannot run Analyze with unsaved scenes"
                });
                return(m_Results);
            }

            CalculateInputDefinitions(settings);
            var context = GetBuildContext(settings);

            RefreshBuild(context);
            ConvertBundleNamesToGroupNames(context);

            m_Results = (from bundleBuild in m_AllBundleInputDefs
                         let bundleName = bundleBuild.assetBundleName
                                          from asset in bundleBuild.assetNames
                                          select new AnalyzeResult {
                resultName = bundleName + kDelimiter + "Explicit" + kDelimiter + asset
            }).ToList();

            if (m_ExtractData.WriteData != null)
            {
                m_Results.AddRange((from fileToBundle in m_ExtractData.WriteData.FileToBundle
                                    from guid in GetImplicitGuidsForBundle(fileToBundle.Key)
                                    let bundleName = fileToBundle.Value
                                                     let assetPath = AssetDatabase.GUIDToAssetPath(guid.ToString())
                                                                     where AddressableAssetUtility.IsPathValidForEntry(assetPath)
                                                                     select new AnalyzeResult
                {
                    resultName = bundleName + kDelimiter + "Implicit" + kDelimiter + assetPath
                }).ToList());
            }

            if (m_Results.Count == 0)
            {
                m_Results.Add(noErrors);
            }

            return(m_Results);
        }
Beispiel #19
0
        public void CreateApplication(string appName, IEnumerable <Module> modules)
        {
            if (string.IsNullOrEmpty(appName))
            {
                result = false;
                return;
            }

            var createAppPath = Path.Combine(Directory.GetParent(_originalPath).FullName, appName);

            //OriginalSourceのコピー
            CopyOriginal(appName, createAppPath);

            //ソースコード作成
            var mainWindowDirectoryPath = Path.Combine(createAppPath, appName);
            var projectFilePath         = Path.Combine(mainWindowDirectoryPath, appName + @".csproj");
            var fullPath    = Path.Combine(mainWindowDirectoryPath, _mainWindowFileName);
            var oldTextList = new List <string>
            {
                @"//CreateTypeArray"
                , @"//DefinitionTypeArray"
                , @"//GetExecuteMethod"
                , @"//MethodInvoke"
                , @"//ConvertReturnValue"
            };

            var newTextList = new List <string>
            {
                @"var types = new Type[2];"
                , @"types[0] = typeof(string);" + Environment.NewLine + @"types[1] = typeof(int);"
                , @"var mainMethod = type.GetMethod(""Main"", types);"
                , @"var ret = mainMethod.Invoke(obj, new object[2] { ""aa"",100 });"
                , @"MessageBox.Show(Convert.ToString(ret));"
            };

            //置換
            ReplaceClassFile(fullPath, oldTextList, newTextList);

            //ビルド
            BuildUtility.BuildProject(projectFilePath);
            result = true;

            return;
        }
Beispiel #20
0
    void OnGUI()
    {
        EditorGUILayout.Space();
        GUILayout.Label("Please Enter Changelog Before Build!");
        GUILayout.Label(AppInfo.productName, EditorStyles.boldLabel);
        GUILayout.Label(AppInfo.buildDateAndCount, EditorStyles.boldLabel);
        EditorGUILayout.Space();

        changeLogString = EditorGUILayout.TextArea(changeLogString, GUILayout.MinHeight(200));

        if (GUILayout.Button("Build"))
        {
            // If nothing is typed then do nothing
            if (changeLogString == "")
            {
                return;
            }

            BuildFileExt.EditChangelog(changelogPath, changeLogString);
            BuildUtility.m_Build();
            this.Close();
        }
    }
        static void OnPostHeaderGUI(Editor editor)
        {
            var aaSettings = AddressableAssetSettingsDefaultObject.Settings;
            AddressableAssetEntry entry = null;

            if (editor.targets.Length > 0)
            {
                int  addressableCount = 0;
                bool foundValidAsset  = false;
                bool foundAssetGroup  = false;
                foreach (var t in editor.targets)
                {
                    foundAssetGroup |= t is AddressableAssetGroup;
                    foundAssetGroup |= t is AddressableAssetGroupSchema;
                    if (AddressableAssetUtility.GetPathAndGUIDFromTarget(t, out var path, out var guid, out var mainAssetType))
                    {
                        // Is asset
                        if (!BuildUtility.IsEditorAssembly(mainAssetType.Assembly))
                        {
                            foundValidAsset = true;

                            if (aaSettings != null)
                            {
                                entry = aaSettings.FindAssetEntry(guid);
                                if (entry != null && !entry.IsSubAsset)
                                {
                                    addressableCount++;
                                }
                            }
                        }
                    }
                }

                if (foundAssetGroup)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Profile: " + AddressableAssetSettingsDefaultObject.GetSettings(true).profileSettings.
                                    GetProfileName(AddressableAssetSettingsDefaultObject.GetSettings(true).activeProfileId));

                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("System Settings", "MiniButton"))
                    {
                        EditorGUIUtility.PingObject(AddressableAssetSettingsDefaultObject.Settings);
                        Selection.activeObject = AddressableAssetSettingsDefaultObject.Settings;
                    }
                    GUILayout.EndHorizontal();
                }

                if (!foundValidAsset)
                {
                    return;
                }

                if (addressableCount == 0)
                {
                    if (GUILayout.Toggle(false, s_AddressableAssetToggleText, GUILayout.ExpandWidth(false)))
                    {
                        SetAaEntry(AddressableAssetSettingsDefaultObject.GetSettings(true), editor.targets, true);
                    }
                }
                else if (addressableCount == editor.targets.Length)
                {
                    GUILayout.BeginHorizontal();
                    if (!GUILayout.Toggle(true, s_AddressableAssetToggleText, GUILayout.ExpandWidth(false)))
                    {
                        SetAaEntry(aaSettings, editor.targets, false);
                        GUIUtility.ExitGUI();
                    }

                    if (editor.targets.Length == 1 && entry != null)
                    {
                        string newAddress = EditorGUILayout.DelayedTextField(entry.address, GUILayout.ExpandWidth(true));
                        if (newAddress != entry.address)
                        {
                            if (newAddress.Contains("[") && newAddress.Contains("]"))
                            {
                                Debug.LogErrorFormat("Rename of address '{0}' cannot contain '[ ]'.", entry.address);
                            }
                            else
                            {
                                entry.address = newAddress;
                                AddressableAssetUtility.OpenAssetIfUsingVCIntegration(entry.parentGroup, true);
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                else
                {
                    GUILayout.BeginHorizontal();
                    if (s_ToggleMixed == null)
                    {
                        s_ToggleMixed = new GUIStyle("ToggleMixed");
                    }
                    if (GUILayout.Toggle(false, s_AddressableAssetToggleText, s_ToggleMixed, GUILayout.ExpandWidth(false)))
                    {
                        SetAaEntry(AddressableAssetSettingsDefaultObject.GetSettings(true), editor.targets, true);
                    }
                    EditorGUILayout.LabelField(addressableCount + " out of " + editor.targets.Length + " assets are addressable.");
                    GUILayout.EndHorizontal();
                }
                if (entry != null)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label(s_AddressableAllowLocalToggleText, GUILayout.ExpandWidth(false));
                    entry.allowLocalMode = (EnumLocalResourceMode)EditorGUILayout.EnumPopup(entry.allowLocalMode, GUILayout.ExpandWidth(true));
                    GUILayout.EndHorizontal();
                }
            }
        }
        static void OnPostHeaderGUI(Editor editor)
        {
            var aaSettings = AddressableAssetSettingsDefaultObject.Settings;
            AddressableAssetEntry entry = null;

            if (editor.targets.Length > 0)
            {
                int  addressableCount = 0;
                bool foundValidAsset  = false;
                bool foundAssetGroup  = false;
                var  targetInfos      = new List <TargetInfo>();
                foreach (var t in editor.targets)
                {
                    foundAssetGroup |= t is AddressableAssetGroup;
                    foundAssetGroup |= t is AddressableAssetGroupSchema;
                    if (AddressableAssetUtility.GetPathAndGUIDFromTarget(t, out var path, out var guid, out var mainAssetType))
                    {
                        // Is asset
                        if (!BuildUtility.IsEditorAssembly(mainAssetType.Assembly))
                        {
                            foundValidAsset = true;
                            var info = new TargetInfo()
                            {
                                Guid = guid, Path = path, MainAssetType = mainAssetType
                            };

                            if (aaSettings != null)
                            {
                                entry = aaSettings.FindAssetEntry(guid);
                                if (entry != null && !entry.IsSubAsset)
                                {
                                    addressableCount++;
                                    info.Entry = entry;
                                }
                            }
                            targetInfos.Add(info);
                        }
                    }
                }

                if (foundAssetGroup)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Profile: " + AddressableAssetSettingsDefaultObject.GetSettings(true).profileSettings.
                                    GetProfileName(AddressableAssetSettingsDefaultObject.GetSettings(true).activeProfileId));

                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("System Settings", "MiniButton"))
                    {
                        EditorGUIUtility.PingObject(AddressableAssetSettingsDefaultObject.Settings);
                        Selection.activeObject = AddressableAssetSettingsDefaultObject.Settings;
                    }
                    GUILayout.EndHorizontal();
                }

                if (!foundValidAsset)
                {
                    return;
                }

                // Overrides a DisabledScope in the EditorElement.cs that disables GUI drawn in the header when the asset cannot be edited.
                bool prevEnabledState = UnityEngine.GUI.enabled;
                UnityEngine.GUI.enabled = true;

                if (addressableCount == 0)
                {
                    if (GUILayout.Toggle(false, s_AddressableAssetToggleText, GUILayout.ExpandWidth(false)))
                    {
                        SetAaEntry(AddressableAssetSettingsDefaultObject.GetSettings(true), targetInfos, true);
                    }
                }
                else if (addressableCount == editor.targets.Length)
                {
                    GUILayout.BeginHorizontal();
                    if (!GUILayout.Toggle(true, s_AddressableAssetToggleText, GUILayout.ExpandWidth(false)))
                    {
                        SetAaEntry(aaSettings, targetInfos, false);
                        UnityEngine.GUI.enabled = prevEnabledState;
                        GUIUtility.ExitGUI();
                    }

                    if (editor.targets.Length == 1 && entry != null)
                    {
                        string newAddress = EditorGUILayout.DelayedTextField(entry.address, GUILayout.ExpandWidth(true));
                        if (newAddress != entry.address)
                        {
                            if (newAddress.Contains("[") && newAddress.Contains("]"))
                            {
                                Debug.LogErrorFormat("Rename of address '{0}' cannot contain '[ ]'.", entry.address);
                            }
                            else
                            {
                                entry.address = newAddress;
                                AddressableAssetUtility.OpenAssetIfUsingVCIntegration(entry.parentGroup, true);
                            }
                        }
                    }
                    else
                    {
                        EditorGUILayout.LabelField(addressableCount + " out of " + editor.targets.Length + " assets are addressable.");
                    }

                    if (GUILayout.Button("Select"))
                    {
                        SelectEntriesInGroupsWindow(targetInfos);
                    }
                    GUILayout.EndHorizontal();
                }
                else
                {
                    GUILayout.BeginHorizontal();
                    if (s_ToggleMixed == null)
                    {
                        s_ToggleMixed = new GUIStyle("ToggleMixed");
                    }
                    if (GUILayout.Toggle(false, s_AddressableAssetToggleText, s_ToggleMixed, GUILayout.ExpandWidth(false)))
                    {
                        SetAaEntry(AddressableAssetSettingsDefaultObject.GetSettings(true), targetInfos, true);
                    }
                    EditorGUILayout.LabelField(addressableCount + " out of " + editor.targets.Length + " assets are addressable.");
                    if (GUILayout.Button("Select"))
                    {
                        SelectEntriesInGroupsWindow(targetInfos);
                    }
                    GUILayout.EndHorizontal();
                }
                UnityEngine.GUI.enabled = prevEnabledState;
            }
        }
Beispiel #23
0
        public override List <AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings)
        {
            List <AnalyzeResult> results = new List <AnalyzeResult>();

            ClearAnalysis();
            ClearOurData();

            var projectRoot = Application.dataPath.Substring(0, Application.dataPath.Length - "Assets/".Length);

            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);
            }

            // Get all immediate folders in Assets/AutoBundles

            HashSet <string> folderNames = new HashSet <string>();
            var folders = AssetDatabase.GetSubFolders("Assets/" + autoBundlesFolderName);

            foreach (var folder in folders)
            {
                folderNames.Add(Path.GetFileName(folder));
            }

            // Get all addressable groups carrying the (Auto) prefix

            HashSet <string> autoGroups = new HashSet <string>();

            foreach (var group in settings.groups)
            {
                if (group.name.StartsWith(autoGroupPrefix))
                {
                    autoGroups.Add(group.name);
                }
            }

            // Collect all groups that must be created or moved

            foreach (var folder in folderNames)
            {
                var autoName = autoGroupPrefix + folder;
                if (!autoGroups.Contains(autoName))
                {
                    groupsToCreate.Add(autoName);
                    results.Add(new AnalyzeResult()
                    {
                        resultName = "Create group \"" + autoName + "\""
                    });
                }
            }

            // Collect all groups that must be removed

            foreach (var groupName in autoGroups)
            {
                var baseName = groupName.Substring(autoGroupPrefix.Length);
                if (!folderNames.Contains(baseName))
                {
                    groupsToRemove.Add(groupName);
                    results.Add(new AnalyzeResult()
                    {
                        resultName = "Remove group \"" + groupName + "\""
                    });
                }
            }

            // Get all assets

            var allGuids    = AssetDatabase.FindAssets(assetFilter, new [] { "Assets/" + autoBundlesFolderName });
            var neverBundle = new HashSet <string>();

            // Only include assets that pass basic filtering, like file extension.
            // Result is "assetPaths", the authoritative list of assets we're considering bundling.

            var assetPaths = new HashSet <string>();

            foreach (var guid in allGuids)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);

                if (ShouldIgnoreAsset(path))
                {
                    neverBundle.Add(path.ToLower());
                }
                else
                {
                    assetPaths.Add(path);
                }
            }

            // Collect all parents of all assets in preparation for not bundling assets with one ultimate non-scene parent.

            var parents = new Dictionary <string, HashSet <string> >(); // Map from asset guid to all its parents

            foreach (var path in assetPaths)
            {
                var dependencies = AssetDatabase.GetDependencies(path);

                foreach (var asset in dependencies)
                {
                    if (asset == path)
                    {
                        // Ignore self
                        continue;
                    }

                    if (ShouldIgnoreAsset(asset))
                    {
                        continue;
                    }

                    if (!parents.ContainsKey(asset))
                    {
                        parents.Add(asset, new HashSet <string>());
                    }
                    parents[asset].Add(path);
                }
            }

            // Unbundle assets with zero parents

            foreach (var asset in assetPaths)
            {
                if (!parents.ContainsKey(asset))
                {
                    neverBundle.Add(asset.ToLower());
                }
            }

            Debug.Log(neverBundle.Count + " asset have zero parents and won't be bundled");
            int floor = neverBundle.Count;

            // Unbundle assets with one parent

            foreach (var asset in assetPaths)
            {
                if (parents.ContainsKey(asset) && parents[asset].Count == 1)
                {
                    neverBundle.Add(asset.ToLower());
                }
            }

            Debug.Log((neverBundle.Count - floor) + " asset have one parent and won't be bundled");
            floor = neverBundle.Count;

            // Unbundle assets with one ultimate parent

            var ultimateParents = new Dictionary <string, HashSet <string> >();

            foreach (var asset in assetPaths)
            {
                if (neverBundle.Contains(asset.ToLower()))
                {
                    continue;
                }

                ultimateParents[asset] = new HashSet <string>();

                // Iterate all the way to the top for this asset. Assemble a list of all ultimate parents of this asset.

                var parentsToCheck = new List <string>();
                parentsToCheck.AddRange(parents[asset].ToList());

                while (parentsToCheck.Count != 0)
                {
                    var checking = parentsToCheck[0];
                    parentsToCheck.RemoveAt(0);

                    if (!parents.ContainsKey(checking))
                    {
                        // If asset we're checking doesn't itself have any parents, this is the end.
                        ultimateParents[asset].Add(checking);
                    }
                    else
                    {
                        parentsToCheck.AddRange(parents[checking]);
                    }
                }
            }

            // Unbundle all assets that don't have two or more required objects as ultimate parents.
            // Objects with one included parent will still get included if needed, just not as a separate Addressable.

            foreach (KeyValuePair <string, HashSet <string> > pair in ultimateParents)
            {
                int requiredParents = 0;
                foreach (var ultiParent in pair.Value)
                {
                    if (AlwaysIncludeAsset(ultiParent))
                    {
                        requiredParents++;
                    }
                }

                if (requiredParents <= 1)
                {
                    neverBundle.Add(pair.Key.ToLower());
                }
            }

            Debug.Log((neverBundle.Count - floor) + " asset have zero or one ultimate parents and won't be bundled");
            floor = neverBundle.Count;

            // Skip assets that are too small. This is a tradeoff between individual access to files,
            // versus the game not having an open file handle for every single 2 KB thing. We're choosing
            // to duplicate some things by baking them into multiple bundles, even though it requires
            // more storage and bandwidth.

            int tooSmallCount = 0;

            foreach (var asset in assetPaths)
            {
                if (neverBundle.Contains(asset.ToLower()))
                {
                    continue;
                }
                var diskPath = projectRoot + "/" + asset;
                var fileInfo = new System.IO.FileInfo(diskPath);
                if (fileInfo.Length < 10000)
                {
                    tooSmallCount++;
                    neverBundle.Add(asset.ToLower());
                }
            }

            Debug.Log(tooSmallCount + " assets are too small and won't be bundled");

            // Collect all assets to create as addressables

            string preamble         = "Assets/" + autoBundlesFolderName + "/";
            var    expresslyBundled = new HashSet <string>();

            foreach (var folder in folderNames)
            {
                var assetGuids = AssetDatabase.FindAssets(assetFilter, new [] { "Assets/" + autoBundlesFolderName + "/" + folder });

                // Schedule creation/moving of assets that exist

                foreach (var guid in assetGuids)
                {
                    var addrPath = AssetDatabase.GUIDToAssetPath(guid);

                    // Skip assets we're never bundling

                    string lowerPath = addrPath.ToLower();
                    if (neverBundle.Contains(lowerPath) && !AlwaysIncludeAsset(lowerPath))
                    {
                        continue;
                    }

                    // Remove the Assets/AutoBundles/ part of assets paths.

                    var shortPath = addrPath;

                    if (shortPath.StartsWith(preamble))
                    {
                        shortPath = shortPath.Substring(preamble.Length);
                    }

                    // Create asset creation/moving action.

                    string autoGroup = autoGroupPrefix + folder;

                    assetActions.Add(new AssetAction()
                    {
                        create          = true,
                        inGroup         = autoGroup,
                        assetGuid       = guid,
                        addressablePath = shortPath
                    });

                    AddressableAssetEntry entry = settings.FindAssetEntry(guid);
                    if (entry == null)
                    {
                        results.Add(new AnalyzeResult()
                        {
                            resultName = "Add:" + shortPath
                        });
                    }
                    else
                    {
                        results.Add(new AnalyzeResult()
                        {
                            resultName = "Keep or move:" + shortPath
                        });
                    }

                    expresslyBundled.Add(shortPath);
                }
            }

            // Schedule removal of assets in auto folders that exist as addressables but aren't expressly bundled.

            foreach (var folder in folderNames)
            {
                string autoName = autoGroupPrefix + folder;
                var    group    = settings.FindGroup(autoName);

                if (group != null)
                {
                    List <AddressableAssetEntry> result = new List <AddressableAssetEntry>();
                    group.GatherAllAssets(result, true, false, true);

                    foreach (var entry in result)
                    {
                        if (entry.IsSubAsset)
                        {
                            continue;
                        }
                        if (entry.guid == "")
                        {
                            Debug.Log("Entry has no guid! " + entry.address);
                        }

                        if (!expresslyBundled.Contains(entry.address))
                        {
                            assetActions.Add(new AssetAction()
                            {
                                create          = false,
                                inGroup         = autoName,
                                assetGuid       = entry.guid,
                                addressablePath = entry.address,
                            });

                            // Print removal message without preamble

                            results.Add(new AnalyzeResult()
                            {
                                resultName = "Remove:" + entry.address
                            });
                        }
                    }
                }
            }

            return(results);
        }
 static void Menu_RTS_Tools_BuildScene()
 {
     BuildUtility.BuildScene();
 }
Beispiel #25
0
        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);
        }
        static void PostProcessBundles(AddressableAssetGroup assetGroup, List <string> bundles, IBundleBuildResults buildResult, IWriteData writeData, ResourceManagerRuntimeData runtimeData, List <ContentCatalogDataEntry> locations, FileRegistry registry)
        {
            var schema = assetGroup.GetSchema <BundledAssetGroupSchema>();

            if (schema == null)
            {
                return;
            }

            var path = schema.BuildPath.GetValue(assetGroup.Settings);

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            foreach (var originalBundleName in bundles)
            {
                var newBundleName = originalBundleName;
                var info          = buildResult.BundleInfos[newBundleName];
                ContentCatalogDataEntry dataEntry = locations.FirstOrDefault(s => newBundleName == (string)s.Keys[0]);
                if (dataEntry != null)
                {
                    var requestOptions = new AssetBundleRequestOptions
                    {
                        Crc             = schema.UseAssetBundleCrc ? info.Crc : 0,
                        Hash            = schema.UseAssetBundleCache ? info.Hash.ToString() : "",
                        ChunkedTransfer = schema.ChunkedTransfer,
                        RedirectLimit   = schema.RedirectLimit,
                        RetryCount      = schema.RetryCount,
                        Timeout         = schema.Timeout,
                        BundleName      = Path.GetFileName(info.FileName),
                        BundleSize      = GetFileSize(info.FileName)
                    };
                    dataEntry.Data = requestOptions;

                    int      extensionLength         = Path.GetExtension(originalBundleName).Length;
                    string[] deconstructedBundleName = originalBundleName.Substring(0, originalBundleName.Length - extensionLength)
                                                       .Split('_');
                    deconstructedBundleName[0] = assetGroup.Name
                                                 .Replace(" ", "")
                                                 .Replace('\\', '/')
                                                 .Replace("//", "/")
                                                 .ToLower();

                    string reconstructedBundleName = string.Join("_", deconstructedBundleName) + ".bundle";

                    newBundleName        = BuildUtility.GetNameWithHashNaming(schema.BundleNaming, info.Hash.ToString(), reconstructedBundleName);
                    dataEntry.InternalId = dataEntry.InternalId.Remove(dataEntry.InternalId.Length - originalBundleName.Length) + newBundleName;

                    if (dataEntry.InternalId.StartsWith("http:\\"))
                    {
                        dataEntry.InternalId = dataEntry.InternalId.Replace("http:\\", "http://").Replace("\\", "/");
                    }
                }
                else
                {
                    Debug.LogWarningFormat("Unable to find ContentCatalogDataEntry for bundle {0}.", newBundleName);
                }

                var targetPath = Path.Combine(path, newBundleName);
                if (!Directory.Exists(Path.GetDirectoryName(targetPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                }
                File.Copy(Path.Combine(assetGroup.Settings.buildSettings.bundleBuildPath, originalBundleName), targetPath, true);
                registry.AddFile(targetPath);
            }
        }
Beispiel #27
0
 /// <summary>
 /// Renvoie la position passée en paramètre alignée à la grille de cette instance de BuildHandler.
 /// </summary>
 /// <returns>La position alignée à la grille.</returns>
 /// <param name="nonSnapPosition">Une position à aligner à la grille.</param>
 Vector3 GetSnappedPosition(Vector3 nonSnapPosition)
 {
     return(BuildUtility.RoundPosition(nonSnapPosition, snapValues));
 }
Beispiel #28
0
 /// <summary>
 /// Called by Unity before a build is started.
 /// Prepares the project for building by (temporarily) removing all nested prefab data.
 /// </summary>
 public void OnPreprocessBuild(BuildTarget target, string path)
 {
     BuildUtility.PreprocessBuild();
 }
Beispiel #29
0
 /// <summary>
 /// Preprocesses the project for a build on Unity Cloud Build.
 /// Will remove all nested prefab data from the project, without creating any backup or restore point.
 /// Set this method as Pre-Export Method in the Advanced Options of your Cloud Build config: NestedPrefabsCloudBuildProcessor.PreExportMethod
 /// </summary>
 public static void PreExportMethod()
 {
     BuildUtility.PreprocessCloudBuild();
 }
Beispiel #30
0
    /// <summary>
    /// Crée un bâtiment sur cette instance du BuildHandler.
    /// </summary>
    /// <param name="buildToCreate">Le prefab du bâtiment à créer.</param>
    /// <param name="buildPosition">La position à laquelle le bâtiment sera instancié.</param>
    public void CreateBuild(Build buildToCreate, Vector3 buildPosition)
    {
        if (buildToCreate.Size.x <= 0 && buildToCreate.Size.y <= 0 && buildToCreate.Size.z <= 0)
        {
            throw new System.InvalidOperationException("Build hasn't correct size: " + buildToCreate.Size);
        }

        Vector3 snappedTransform = GetSnappedPosition(myTransform.position);
        Vector3 delta            = myTransform.position - snappedTransform;

        // position aligné à la grille.
        Vector3 snappedPosition = GetSnappedPosition(buildPosition, delta);
        // position local au sol aligné à la grille
        Vector3 localSnappedPosition = GetSnappedPosition(buildPosition - myTransform.position, delta);

        Debug.Log("Given Position: " + buildPosition);
        Debug.Log("Snapped Position: " + snappedPosition);
        Debug.Log("Local Snapped Position: " + localSnappedPosition);

        // calcul la position a la quel doit être instancié le batiment
        Vector3 instantiatePosition = BuildUtility.GetBuildWorldPosition(snappedPosition, buildToCreate.Size) /* + delta*/;

        Debug.Log("Instantiate Position: " + instantiatePosition);

        // index en x du batiment
        // on divise la position local par la valeur du snap pour avoir un index allant de -cutCount / 2 jusqua cutCount / 2 - 1.
        // et le cutCount est la pour decaler l'index afin d'obtenir un index allant de 0 à cutCount.
        int locX = Mathf.RoundToInt(localSnappedPosition.x / snapValues.x) + (spacingCountX / 2);
        // index en y du batiment
        int locZ = Mathf.RoundToInt(localSnappedPosition.z / snapValues.y) + (spacingCountY / 2);

        int sizeX = Mathf.RoundToInt(buildToCreate.Size.x / snapValues.x);
        int sizeY = Mathf.RoundToInt(buildToCreate.Size.z / snapValues.y);

        Debug.Log("LocX: " + locX + " LocZ: " + locZ);
        Debug.Log("SizeX: " + sizeX + " SizeY" + sizeY);

        // en cas de non association parfaite possible entre la taille du prefab et la snapValues alors on arrêtera la création.
        if (useSecureSizes && (buildToCreate.Size.x % snapValues.x != 0 || buildToCreate.Size.z % snapValues.y != 0))
        {
            Debug.Log("Création impossible la taille du bâtiment ne correspond pas à la grille");
            return;
        }

        Coord[] occupiedCoords = BuildUtility.GetOccupiedBuildCoords(locX, locZ, sizeX, sizeY);

        if (IsInCellule(occupiedCoords) && !IsOccupiedCoord(occupiedCoords))
        {
            // instanciation du batiment
            //Build instantiatedBuild = Instantiate(buildToCreate, instantiatePosition, Quaternion.identity);

            if (!buildPool.IsInPool(buildToCreate))
            {
                buildPool.AddPrefabReference(buildToCreate);
            }

            Build instantiatedBuild = buildPool.GetObject(buildToCreate);
            instantiatedBuild.buildTransform.position = instantiatePosition;

            if (instantiatedBuild.ApplyBuildHandlerScale)
            {
                // assignation de la taille actuelle qu'a le bâtiment
                Vector3 currentBuildLocalScale = instantiatedBuild.buildTransform.localScale;
                // calcul de la nouvelle taille
                Vector3 newBuildLocalScale = new Vector3(currentBuildLocalScale.x * myTransform.localScale.x, currentBuildLocalScale.y * myTransform.localScale.y, currentBuildLocalScale.z * myTransform.localScale.z);
                // assigne la nouvelle taille au bâtiment
                instantiatedBuild.buildTransform.localScale = newBuildLocalScale;
            }

            // initialisation du batiment
            instantiatedBuild.BuildInitialisation(locX, locZ, sizeX, sizeY, snappedPosition + offset, occupiedCoords);
            // ajout du batiement a la liste des batiments présents sur ce gameobject
            builds.Add(instantiatedBuild);
            // assigne le transform parent du build
            // je fais cette manipulation après l'instantiation car sinon le build aura en plus de la scale, celle du transform de cet objet
            // ce qui risque de poser de gros problèmes.
            instantiatedBuild.buildTransform.SetParent(myTransform);

            Debug.Log(instantiatedBuild.ToString());
        }
    }