public static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath) {
			// BuiltTarget.iOS is not defined in Unity 4, so we just use strings here
			if (buildTarget.ToString () == "iOS" || buildTarget.ToString () == "iPhone") {
				PrepareProject (buildPath);
				PreparePlist (buildPath);
			}
		}
        public static void OnPostProcessBuild(BuildTarget target, string path)
        {
            // If integrating with facebook on any platform, throw a warning if the app id is invalid
            if (!Facebook.Unity.FacebookSettings.IsValidAppId)
            {
                Debug.LogWarning("You didn't specify a Facebook app ID.  Please add one using the Facebook menu in the main Unity editor.");
            }
            // Unity renamed build target from iPhone to iOS in Unity 5, this keeps both versions happy
            if (target.ToString() == "iOS" || target.ToString() == "iPhone")
            {
                UpdatePlist(path);
                FixupFiles.FixSimulator(path);
                FixupFiles.AddVersionDefine(path);
                FixupFiles.FixColdStart(path);
            }

            if (target == BuildTarget.Android)
            {
                // The default Bundle Identifier for Unity does magical things that causes bad stuff to happen
                if (PlayerSettings.bundleIdentifier == "com.Company.ProductName")
                {
                    Debug.LogError("The default Unity Bundle Identifier (com.Company.ProductName) will not work correctly.");
                }
                if (!FacebookAndroidUtil.IsSetupProperly())
                {
                    Debug.LogError("Your Android setup is not correct. See Settings in Facebook menu.");
                }

                if (!ManifestMod.CheckManifest())
                {
                    // If something is wrong with the Android Manifest, try to regenerate it to fix it for the next build.
                    ManifestMod.GenerateManifest();
                }
            }
        }
Пример #3
0
 protected bool VerifyAssembly(BuildTarget target, string assembly)
 {
     if ((this.m_UnsupportedAssemblies.ContainsKey("*") && this.m_UnsupportedAssemblies["*"].Contains(assembly)) || (this.m_UnsupportedAssemblies.ContainsKey(target.ToString()) && this.m_UnsupportedAssemblies[target.ToString()].Contains(assembly)))
     {
         return false;
     }
     return true;
 }
Пример #4
0
 static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
 {
     if (LunarConsoleSettings.consoleEnabled)
     {
         if (target.ToString() == "iOS" || target.ToString() == "iPhone")
         {
             OnPostprocessIOS(pathToBuiltProject);
         }
     }
 }
		public static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath)
		{
			if (!IsKitOnboarded ("Crashlytics")) {
				Fabric.Internal.Editor.Utils.Warn ("Crashlytics not yet onboarded, skipping post-build steps.");
				return;
			}

			// BuiltTarget.iOS is not defined in Unity 4, so we just use strings here
			if (buildTarget.ToString () == "iOS" || buildTarget.ToString () == "iPhone") {
				CheckiOSVersion ();

				PrepareProject (buildPath);
				PreparePlist (buildPath);
			}
		}
 private static void BuildBundles(BuildTarget target)
 {
     BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.DeterministicAssetBundle;
     string path = DirectoryUtility.AssetBundles() + "/" + target.ToString();
     Directory.CreateDirectory(path);
     BuildPipeline.BuildAssetBundles(path, assetBundleOptions, target);
 }
Пример #7
0
        public static void ChangePlatform(BuildTarget desiredPlatform)
        {
            if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                // They hit cancel in the save dialog
                return;
            }

            if (ProjenyEditorUtil.GetPlatformFromDirectoryName() == desiredPlatform)
            {
                UnityEngine.Debug.Log("Projeny: Already at the desired platform, no need to change project.");
                return;
            }

            var result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequestForPlatform("updateLinks", desiredPlatform));

            if (result.Succeeded)
            {
                result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequestForPlatform("openUnity", desiredPlatform));
            }

            if (result.Succeeded)
            {
                EditorApplication.Exit(0);
            }
            else
            {
                DisplayPrjError(
                    "Changing platform to '{0}'"
                    .Fmt(desiredPlatform.ToString()), result.ErrorMessage);
            }
        }
		public static void OnPostProcessBuild( BuildTarget target, string pathToBuiltProject )
		{
			string 	_targetStr	= target.ToString();

			if (!(_targetStr.Equals("iOS") || _targetStr.Equals("iPhone")))
			{
				Debug.LogWarning("Target is not iPhone. XCodePostProcess will not run");
				return;
			}

			// Create a new project object from build target
			XCProject project = new XCProject( pathToBuiltProject );

			// Find and run through all xcodemods files to patch the project.
			// Please pay attention that ALL xcodemods files in your project folder will be excuted!
			string[] files = Directory.GetFiles( Utility.AssetsUtility.GetProjectPath(), "*.xcodemods", SearchOption.AllDirectories );
			foreach( string file in files ) {
				UnityEngine.Debug.Log("Xcodemods File: "+file);
				project.ApplyMod( file );
			}

			//TODO implement generic settings as a module option
	//		project.overwriteBuildSetting("CODE_SIGN_IDENTITY[sdk=iphoneos*]", "iPhone Distribution", "Release");
			
			// Finally save the xcode project
			project.Save();

		}
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        if(target.ToString()=="StandaloneWindows"){

            string gmlFileName = "my_gestures.gml";
            string coreDllFileName = "GestureworksCore32.dll";

            string pathToNewDataFolder = "";
            string pathToAssetsFolder = UnityEngine.Application.dataPath;
            pathToAssetsFolder = pathToAssetsFolder.Replace("/", "\\");

            //destination /Bin folder
            string[] pathPieces = pathToBuiltProject.Split("/".ToCharArray() );
            string exeName = pathPieces[pathPieces.Length-1];

            exeName = exeName.Trim(".exe".ToCharArray()); // extract the name of the exe to use with the name of the data folder
            for(int i=1; i<pathPieces.Length; i++){
                pathToNewDataFolder += pathPieces[i-1]+"\\"; // this will grab everything except for the last
            }
            pathToNewDataFolder += exeName+"_Data\\";
            //Debug.Log("pathToAssetsFolder: "+pathToAssetsFolder);
            //Debug.Log("pathToNewDataFolder: "+pathToNewDataFolder);

            //PostBuildProcessor window = EditorWindow.GetWindow<PostBuildProcessor> ("Post Build Options");
            FileUtil.CopyFileOrDirectory(pathToAssetsFolder+"\\MyScripts\\"+gmlFileName, pathToNewDataFolder+gmlFileName);
            FileUtil.CopyFileOrDirectory(pathToAssetsFolder+"\\Plugins\\Gestureworks\\Core\\"+coreDllFileName, pathToNewDataFolder+coreDllFileName);

        } else {
            //Debug.Log("Only the Windows platform is supported only with Gestureworks");
        }
    }
        public static void OnPostProcessBuild(BuildTarget target, string path)
        {
            // If integrating with facebook on any platform, throw a warning if the app id is invalid
            if (!FBSettings.IsValidAppId)
            {
                Debug.LogWarning("You didn't specify a Facebook app ID.  Please add one using the Facebook menu in the main Unity editor.");
            }
			// Unity renamed build target from iPhone to iOS in Unity 5, this keeps both versions happy
			if (target.ToString() == "iOS" || target.ToString() == "iPhone")
            {
                UnityEditor.XCodeEditor.XCProject project = new UnityEditor.XCodeEditor.XCProject(path);

                // Find and run through all projmods files to patch the project

                string projModPath = System.IO.Path.Combine(Application.dataPath, "Facebook/Editor/iOS");
                var files = System.IO.Directory.GetFiles(projModPath, "*.projmods", System.IO.SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    project.ApplyMod(Application.dataPath, file);
                }
                project.Save();

                UpdatePlist(path);
                FixupFiles.FixSimulator(path);
                FixupFiles.AddVersionDefine(path);
                FixupFiles.FixColdStart(path);
            }

            if (target == BuildTarget.Android)
            {
                // The default Bundle Identifier for Unity does magical things that causes bad stuff to happen
                if (PlayerSettings.bundleIdentifier == "com.Company.ProductName")
                {
                    Debug.LogError("The default Unity Bundle Identifier (com.Company.ProductName) will not work correctly.");
                }
                if (!FacebookAndroidUtil.IsSetupProperly())
                {
                    Debug.LogError("Your Android setup is not correct. See Settings in Facebook menu.");
                }

                if (!ManifestMod.CheckManifest())
                {
                    // If something is wrong with the Android Manifest, try to regenerate it to fix it for the next build.
                    ManifestMod.GenerateManifest();
                }
            }
        }
    static void BuildBundle(string path, BuildTarget target)
    {
        if (!Directory.Exists (path))
            Directory.CreateDirectory (path);

        BuildPipeline.BuildAssetBundles (path, BuildAssetBundleOptions.None, target);
        Debug.Log (target.ToString ());
    }
        string BuildPlayer(BuildTarget target, BuildOptions options, params string[] levels)
        {
            var output = Path.Combine(OutputDir, target.ToString());
            DirectoryEx.DeleteDirectory(output);

            BuildPipeline.BuildPlayer(levels, output, target,  options);
            return output;
        }
Пример #13
0
 private void DrawPlatformToggle(BuildTarget target, string label)
 {
     // We try to make a unique key for this EditorPref variable
     string key = Prefix + target.ToString ();
     // We define false the default value of the EditorPref if this is not defined
     bool currentValue = EditorPrefs.GetBool (key, false);
     EditorPrefs.SetBool (key, GUILayout.Toggle (currentValue, label));
 }
		public static void OnPostProcessBuild(BuildTarget build, string path)
		{
			//Make sure this build is for iOS.
			//Unity 4 uses 'iPhone' for the enum value; Unity 5 changes it to 'iOS'.
			if (build.ToString() != "iPhone" && build.ToString() != "iOS")
			{
				UnityEngine.Debug.LogWarning("Skillz cannot be set up for a platform other than iOS.");
				return;
			}
			if (Application.platform != RuntimePlatform.OSXEditor)
			{
				UnityEngine.Debug.LogError("Skillz cannot be set up for XCode automatically on a platform other than OSX.");
				return;
			}
			
			//Get whether this is an append build by checking whether a custom file has already been created.
			//If it is, then nothing needs to be modified.
			string checkAppendFilePath = Path.Combine(path, checkAppendFileName);
			FileInfo checkAppend = new FileInfo(checkAppendFilePath);
			if (checkAppend.Exists)
			{
				return;
			}
			
			checkAppend.Create().Close();
			
			bool trySetUp = SetUpOrientation(path) && SetUpSDKFiles(path);
			if (!trySetUp)
			{
				//These failures aren't fatal; the developer can do them manually.
				UnityEngine.Debug.LogWarning("Skillz automated steps failed!");
			}

			//Set up XCode project settings.
			SkillzXCProjEdit editProj = SkillzXCProjEdit.LoadXCProj(path);
			if (editProj == null ||
			    !editProj.AddLinkerFlags() || !editProj.AddSkillzFiles() || !editProj.AddRunScript() ||
			    !editProj.SaveChanges())
			{
				UnityEngine.Debug.LogError("Skillz automated XCode editing failed!");
				return;
			}
		}
		public static void OnPostProcessBuild (BuildTarget _target, string _buildPath) 
		{			
			string 	_targetStr	= _target.ToString();
			
			if (_targetStr.Equals ("iOS") || _targetStr.Equals ("iPhone"))
			{
				iOSPostProcessBuild (_target, _buildPath);
				return;
			}
		}
        public static void OnPostProcessBuild (BuildTarget target, string path)
        {
            // Unity renamed build target from iPhone to iOS in Unity 5, this keeps both versions happy
            if (target.ToString () == "iOS" || target.ToString () == "iPhone") {
                UpdatePlist (path);
            }

            if (target == BuildTarget.Android) {
                // The default Bundle Identifier for Unity does magical things that causes bad stuff to happen
                if (PlayerSettings.bundleIdentifier == "com.Company.ProductName") {
                    Debug.LogError ("The default Unity Bundle Identifier (com.Company.ProductName) will not work correctly.");
                }

                if (!ManifestMod.CheckManifest())
                {
                    // If something is wrong with the Android Manifest, try to regenerate it to fix it for the next build.
                    ManifestMod.GenerateManifest();
                }
            }
        }
Пример #17
0
    //[MenuItem("Game/test")]
    //public static void ExportResource()
    //{
    //    string output = EditorUtility.OpenFolderPanel("Build Assets ", "Assets/StreamingAssets/", "");
    //    if (output.Length == 0)
    //        return;
    //    Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
    //    for (int i=0;i<selection.Length;++i)
    //        BuildPipeline.BuildAssetBundle(selection[i], null, Path.Combine(output,selection[i].name)+".assetbundle", BuildAssetBundleOptions.None);
    //    Selection.objects = selection;
    //}
    /// <summary>
    /// 生成绑定素材
    /// </summary>
    public static void BuildAssetResource(BuildTarget target, bool isWin)
    {
        string output = EditorUtility.OpenFolderPanel("Build Assets ", "Assets/StreamingAssets/", "");
        if (output.Length == 0)
            return;
        string dataPath = output;

        BuildPipeline.BuildAssetBundles(dataPath, BuildAssetBundleOptions.None, target);

        AssetDatabase.Refresh();
        UnityEngine.Debug.Log("BuildAssetResource Success,target="+target.ToString());
    }
Пример #18
0
    //-------------------------------------------------------------------------------------------------------------------------
    public static void Build(string config, string log_filename, BuildTarget target, string output)
    {
        BuildLogger logger = new BuildLogger(log_filename, false);

        logger.Log("Building Platform: " + target.ToString());
        logger.Log("Building Config:   " + config);
        logger.Log("");

        string[] level_list = FindScenes();
        logger.Log("Scenes to be processed: " + level_list.Length);

        foreach (string s in level_list)
        {
            string cutdown_level_name = s.Remove(s.IndexOf(".unity"));
            logger.Log("   " + cutdown_level_name);
        }

        // Make sure the paths exist before building.
        try
        {
            Directory.CreateDirectory(output);
        }
        catch
        {
            logger.Log("Failed to create directories: " + output);
        }

        string results = "";

        try
        {
            results = BuildPipeline.BuildPlayer(level_list, output, target, BuildOptions.None);
        }
        catch
        {
            logger.Log("Errors Found.");
            logger.Log(results);
            logger.Close();
        }

        logger.Log("");

        if (results.Length == 0)
            logger.Log("No Build Errors");
        else
        {
            logger.Log("Errors Found.");
            logger.Log(results);
        }

        logger.Close();
    }
	public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform)
	{
		// This method almost exactly copies CSharpLanguage.CreateCompiler(...)

		if (!buildingForEditor && targetPlatform.ToString().Contains("MetroPlayer") &&
			(PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCore ||
			 (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCorePartially
			  && !island._output.Contains("Assembly-CSharp-firstpass.dll"))))
		{
			return new MicrosoftCSharpCompiler(island);
		}
		return new CustomCSharpCompiler(island, false); // MonoCSharpCompiler is replaced with CustomCSharpCompiler
	}
        public static void OnPostProcessBuild(BuildTarget target, string path)
        {
            if (target.ToString() == "iOS" || target.ToString() == "iPhone")
            {
                // Create a new project object from build target
                XCProject project = new XCProject( path );
                //project.AddFrameworkSearchPaths (System.IO.Path.Combine (Application.dataPath, "iOSProjectFix/Editor/VKSdk"));
                //project.AddFrameworkSearchPaths ("iOSProjectFix/Editor/VKSdk");
                string[] files = Directory.GetFiles( Application.dataPath, "*.vkprojmods", SearchOption.AllDirectories );
                foreach( string file in files ) {
                    UnityEngine.Debug.Log("ProjMod File: "+file);
                    project.ApplyMod( file );
                }

                project.Save();

                FixupFiles.FixSimulator(path);

            }
            if (target.ToString () == "WP8Player") {
                FixupFiles.AddIdCapWebBrowserComponent(path);
            }
        }
        public void SwitchTargetTo(BuildTarget targetTo)
        {
            if (targetTo == CurrentBuildTarget) return;

            Debug.LogFormat("{0} => {1}", CurrentBuildTarget.ToString(), targetTo.ToString());

            var libraryPathFrom = LibraryPath(CurrentBranchName, CurrentBuildTarget);
            var libraryPathTo = LibraryPath(CurrentBranchName, targetTo);
            SwitchLibrary(libraryPathFrom, libraryPathTo);
            if (!EditorUserBuildSettings.SwitchActiveBuildTarget(targetTo))
            {
                Directory.Delete(libraryPathFrom, true);
                UpdateCachedLibrariesInfo();
            }
        }
Пример #22
0
 protected void VerifyBuildInternal(BuildTarget target, string managedDllFolder)
 {
     foreach (string str in Directory.GetFiles(managedDllFolder))
     {
         if (str.EndsWith(".dll"))
         {
             string fileName = Path.GetFileName(str);
             if (!this.VerifyAssembly(target, fileName))
             {
                 object[] args = new object[] { fileName, target.ToString() };
                 Debug.LogWarningFormat("{0} assembly is referenced by user code, but is not supported on {1} platform. Various failures might follow.", args);
             }
         }
     }
 }
Пример #23
0
 static void OnPostProcessBuild(BuildTarget target, string path)
 {
     Setup.OnPostProcessBuild(target, path);
     if (target.ToString() == "Android")
     {
         var manifest = Sdkbox.Android.Manifest.Open();
         if (null != manifest)
         {
             manifest.OverrideUnityNativeActivity();
             manifest.AddPermission("com.android.vending.BILLING");
             manifest.Close();
         }
         else
         {
             Debug.Log("Failed to open AndroidManifest.xml");
         }
     }
 }
Пример #24
0
 public static void Build(BuildTarget buildTarget, string productName, string[] scenePaths, string companyName, string bundleId)
 {
     if (EditorUserBuildSettings.activeBuildTarget != buildTarget) {
         EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget);
     }
     if (!Directory.Exists(DirectoryName)) {
         Directory.CreateDirectory(DirectoryName);
     }
     PlayerSettings.productName = productName;
     productName = productName.Replace(" ", null);
     if (string.IsNullOrEmpty(bundleId)) {
         bundleId = productName;
     }
     PlayerSettings.strippingLevel = StrippingLevel.UseMicroMSCorlib;
     PlayerSettings.bundleIdentifier = "com." + companyName + "." + bundleId;
     string appPath = Path.Combine(DirectoryName, string.Format("{0}-{1}", buildTarget.ToString(), productName));
     BuildPipeline.BuildPlayer(scenePaths, appPath, buildTarget, BuildOptions.ShowBuiltPlayer);
 }
Пример #25
0
 private void LayoutTarget(BuildTarget target)
 {
     string path = EditorUserBuildSettings.GetBuildLocation(target);
     if (!System.String.IsNullOrEmpty(path)) {
         EditorGUILayout.BeginHorizontal();
         string name = target.ToString();
         if (EditorUserBuildSettings.activeBuildTarget == target) {
             name = name + " (current)";
         };
         EditorGUILayout.LabelField(name);
      	  	if (System.IO.File.Exists(path) || System.IO.Directory.Exists(path)) {
             if (GUILayout.Button("Delete Build")) {
        		  		FileUtil.DeleteFileOrDirectory(path);
             }
       	 	}
         EditorGUILayout.EndHorizontal();
         EditorGUILayout.LabelField(path);
     }
 }
Пример #26
0
		protected void VerifyBuildInternal(BuildTarget target, string managedDllFolder)
		{
			string[] files = Directory.GetFiles(managedDllFolder);
			for (int i = 0; i < files.Length; i++)
			{
				string text = files[i];
				if (text.EndsWith(".dll"))
				{
					string fileName = Path.GetFileName(text);
					if (!this.VerifyAssembly(target, fileName))
					{
						Debug.LogWarningFormat("{0} assembly is referenced by user code, but is not supported on {1} platform. Various failures might follow.", new object[]
						{
							fileName,
							target.ToString()
						});
					}
				}
			}
		}
Пример #27
0
 public static string GetBuildDir(BuildTarget target)
 {
     return(RES_OUTPUT_PATH + target.ToString());
 }
Пример #28
0
 static void OnPostProcessBuildPlayer(BuildTarget target, string buildPath)
 {
     WriteBuildLog(buildPath, target.ToString());
 }
Пример #29
0
        // This function is responsible for providing all the subscenes to the build.
        //
        // The way these files get generated is that we have a SceneWithBuildConfiguration file, (which is a bit of a hack to work around the inability for scriptable importers to take arguments, so
        // instead we create a different file that points to the scene we want to import, and points to the buildconfiguration we want to import it for).   The SubsceneImporter will import this file,
        // and it will make 3 (relevant) kind of files:
        // - headerfile
        // - entitybinaryformat file (the actual entities payloads)
        // - a SerializedFile that has an array of UnityEngine.Object PPtrs that are used by this entity file.
        //
        // The first two we deal with very simply: they just need to be copied into the build, and we're done.
        // the third one, we will feed as input to the Scriptable build pipeline (which is actually about creating assetbundles), and create an assetbundle that
        // has all those objects in it that the 3rd file referred to.  We do this with a batch api, first we loop through all subscenes, and register with this batch
        // api which assetbundles we'd like to see produced, and then at the end, we say "okay make them please".  this assetbundle creation api has a caching system
        // that is separate from the assetpipeline caching system, so if all goes well, the call to produce these assetbundles will return very fast and did nothing.
        //
        // The reason for the strange looking api, where a two callbacks get passed in is to make integration of the new incremental buildpipeline easier, as this code
        // needs to be compatible both with the current buildpipeline in the dots-repo, as well as with the incremental buildpipeline.  When that is merged, we can simplify this.
        public static void PrepareAdditionalFiles(string buildConfigurationGuid, string[] scenePathsForBuild, BuildTarget target, Action <string, string> RegisterFileCopy, string outputStreamingAssetsDirectory, string buildWorkingDirectory)
        {
            if (target == BuildTarget.NoTarget)
            {
                throw new InvalidOperationException($"Invalid build target '{target.ToString()}'.");
            }

            if (target != EditorUserBuildSettings.activeBuildTarget)
            {
                throw new InvalidOperationException($"ActiveBuildTarget must be switched before the {nameof(SubSceneBuildCode)} runs.");
            }

            var content             = new BundleBuildContent(new AssetBundleBuild[0]);
            var bundleNames         = new HashSet <string>();
            var subSceneGuids       = scenePathsForBuild.SelectMany(scenePath => SceneMetaDataImporter.GetSubSceneGuids(AssetDatabase.AssetPathToGUID(scenePath))).Distinct().ToList();
            var subScenePaths       = new Dictionary <Hash128, string>();
            var dependencyInputData = new Dictionary <SceneSection, SectionDependencyInfo>();
            var refExt    = EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesUnityObjectReferences);
            var headerExt = EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesHeader);
            var binaryExt = EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesBinary);

            var group      = BuildPipeline.GetBuildTargetGroup(target);
            var parameters = new BundleBuildParameters(target, @group, buildWorkingDirectory)
            {
                BundleCompression = BuildCompression.LZ4Runtime
            };

            var requiresRefresh       = false;
            var sceneBuildConfigGuids = new NativeArray <GUID>(subSceneGuids.Count, Allocator.TempJob);

            for (int i = 0; i != sceneBuildConfigGuids.Length; i++)
            {
                sceneBuildConfigGuids[i] = SceneWithBuildConfigurationGUIDs.EnsureExistsFor(subSceneGuids[i], new Hash128(buildConfigurationGuid), out var thisRequiresRefresh);
                requiresRefresh         |= thisRequiresRefresh;
            }
            if (requiresRefresh)
            {
                AssetDatabase.Refresh();
            }

            var artifactHashes = new NativeArray <UnityEngine.Hash128>(subSceneGuids.Count, Allocator.TempJob);

            AssetDatabaseCompatibility.ProduceArtifactsRefreshIfNecessary(sceneBuildConfigGuids, typeof(SubSceneImporter), artifactHashes);

            for (int i = 0; i != sceneBuildConfigGuids.Length; i++)
            {
                var sceneGuid            = subSceneGuids[i];
                var sceneBuildConfigGuid = sceneBuildConfigGuids[i];
                var artifactHash         = artifactHashes[i];

                bool foundEntityHeader = false;
                AssetDatabaseCompatibility.GetArtifactPaths(artifactHash, out var artifactPaths);
                foreach (var artifactPath in artifactPaths)
                {
                    //@TODO: This looks like a workaround. Whats going on here?
                    var ext = Path.GetExtension(artifactPath).Replace(".", "");
                    if (ext == headerExt)
                    {
                        foundEntityHeader = true;

                        if (!string.IsNullOrEmpty(artifactPaths.FirstOrDefault(a => a.EndsWith(refExt))))
                        {
                            subScenePaths[sceneGuid] = artifactPath;
                        }
                        else
                        {
                            //if there are no reference bundles, then deduplication can be skipped
                            var destinationFile = EntityScenesPaths.RelativePathFolderFor(sceneGuid, EntityScenesPaths.PathType.EntitiesHeader, -1);
                            DoCopy(RegisterFileCopy, outputStreamingAssetsDirectory, artifactPath, destinationFile);
                        }
                    }
                    else if (ext == binaryExt)
                    {
                        var destinationFile = EntityScenesPaths.RelativePathFolderFor(sceneGuid, EntityScenesPaths.PathType.EntitiesBinary, EntityScenesPaths.GetSectionIndexFromPath(artifactPath));
                        DoCopy(RegisterFileCopy, outputStreamingAssetsDirectory, artifactPath, destinationFile);
                    }

                    if (ext == refExt)
                    {
                        content.CustomAssets.Add(new CustomContent
                        {
                            Asset     = sceneBuildConfigGuid,
                            Processor = (guid, processor) =>
                            {
                                var sectionIndex = EntityScenesPaths.GetSectionIndexFromPath(artifactPath);
                                processor.GetObjectIdentifiersAndTypesForSerializedFile(artifactPath, out ObjectIdentifier[] objectIds, out Type[] types);
Пример #30
0
 protected bool VerifyAssembly(BuildTarget target, string assembly)
 {
     return((!this.m_UnsupportedAssemblies.ContainsKey("*") || !this.m_UnsupportedAssemblies["*"].Contains(assembly)) && (!this.m_UnsupportedAssemblies.ContainsKey(target.ToString()) || !this.m_UnsupportedAssemblies[target.ToString()].Contains(assembly)));
 }
Пример #31
0
            internal static BuildPlayerOptions GetBuildPlayerOptionsInternal(bool askForBuildLocation, BuildPlayerOptions defaultBuildPlayerOptions)
            {
                var options = defaultBuildPlayerOptions;

                bool updateExistingBuild = false;

                BuildTarget      buildTarget      = EditorUserBuildSettingsUtils.CalculateSelectedBuildTarget();
                BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;

                // Pick location for the build
                string newLocation          = "";
                bool   installInBuildFolder = EditorUserBuildSettings.installInBuildFolder && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTargetGroup, buildTarget) && (Unsupported.IsSourceBuild() ||
                                                                                                                                                                                     IsMetroPlayer(buildTarget));

                //Check if Lz4 is supported for the current buildtargetgroup and enable it if need be
                if (PostprocessBuildPlayer.SupportsLz4Compression(buildTargetGroup, buildTarget))
                {
                    if (EditorUserBuildSettings.GetCompressionType(buildTargetGroup) == Compression.Lz4)
                    {
                        options.options |= BuildOptions.CompressWithLz4;
                    }
                    else if (EditorUserBuildSettings.GetCompressionType(buildTargetGroup) == Compression.Lz4HC)
                    {
                        options.options |= BuildOptions.CompressWithLz4HC;
                    }
                }

                bool developmentBuild = EditorUserBuildSettings.development;

                if (developmentBuild)
                {
                    options.options |= BuildOptions.Development;
                }
                if (EditorUserBuildSettings.datalessPlayer && developmentBuild)
                {
                    options.options |= BuildOptionsExperimental.DatalessPlayer;
                }
                if (EditorUserBuildSettings.allowDebugging && developmentBuild)
                {
                    options.options |= BuildOptions.AllowDebugging;
                }
                if (EditorUserBuildSettings.symlinkLibraries)
                {
                    options.options |= BuildOptions.SymlinkLibraries;
                }
                if (EditorUserBuildSettings.enableHeadlessMode)
                {
                    options.options |= BuildOptions.EnableHeadlessMode;
                }
                if (EditorUserBuildSettings.connectProfiler && (developmentBuild || buildTarget == BuildTarget.WSAPlayer))
                {
                    options.options |= BuildOptions.ConnectWithProfiler;
                }
                if (EditorUserBuildSettings.buildScriptsOnly)
                {
                    options.options |= BuildOptions.BuildScriptsOnly;
                }

                if (installInBuildFolder)
                {
                    options.options |= BuildOptions.InstallInBuildFolder;
                }

                if (!installInBuildFolder)
                {
                    if (askForBuildLocation && !PickBuildLocation(buildTargetGroup, buildTarget, options.options, out updateExistingBuild))
                    {
                        throw new BuildMethodException();
                    }

                    newLocation = EditorUserBuildSettings.GetBuildLocation(buildTarget);

                    if (newLocation.Length == 0)
                    {
                        throw new BuildMethodException("Build location for buildTarget " + buildTarget.ToString() + "is not valid.");
                    }

                    if (!askForBuildLocation)
                    {
                        switch (UnityEditorInternal.InternalEditorUtility.BuildCanBeAppended(buildTarget, newLocation))
                        {
                        case CanAppendBuild.Unsupported:
                            break;

                        case CanAppendBuild.Yes:
                            updateExistingBuild = true;
                            break;

                        case CanAppendBuild.No:
                            if (!PickBuildLocation(buildTargetGroup, buildTarget, options.options, out updateExistingBuild))
                            {
                                throw new BuildMethodException();
                            }

                            newLocation = EditorUserBuildSettings.GetBuildLocation(buildTarget);
                            if (!BuildLocationIsValid(newLocation))
                            {
                                throw new BuildMethodException("Build location for buildTarget " + buildTarget.ToString() + "is not valid.");
                            }

                            break;
                        }
                    }
                }

                if (updateExistingBuild)
                {
                    options.options |= BuildOptions.AcceptExternalModificationsToPlayer;
                }

                options.target                  = buildTarget;
                options.targetGroup             = buildTargetGroup;
                options.locationPathName        = EditorUserBuildSettings.GetBuildLocation(buildTarget);
                options.assetBundleManifestPath = null;

                // Build a list of scenes that are enabled
                ArrayList scenesList = new ArrayList();

                EditorBuildSettingsScene[] editorScenes = EditorBuildSettings.scenes;
                foreach (EditorBuildSettingsScene scene in editorScenes)
                {
                    if (scene.enabled)
                    {
                        scenesList.Add(scene.path);
                    }
                }

                options.scenes = scenesList.ToArray(typeof(string)) as string[];

                return(options);
            }
Пример #32
0
        private static void OnPostProcessBuild(BuildTarget target, string targetPathFilename)
        {
            if (!EditorSettings.Instance.BuildPlayer_CopyBinaries)
            {
                return;
            }

            if (target != BuildTarget.StandaloneWindows64 && target != BuildTarget.StandaloneWindows)
            {
                Debug.LogWarning(GUI.AddColorTag("Copy AGX Dynamics binaries - unsupported build target: ",
                                                 Color.red) +
                                 target.ToString());
                return;
            }

            var nativeIsX64 = agx.agxSWIG.isBuiltWith(agx.BuildConfiguration.USE_64BIT_ARCHITECTURE);

            if ((target == BuildTarget.StandaloneWindows64) != nativeIsX64)
            {
                Debug.LogWarning(GUI.AddColorTag("Copy AGX Dynamics binaries - x86/x64 architecture mismatch: ",
                                                 Color.red) +
                                 "Build target = " +
                                 target.ToString() +
                                 ", AGX Dynamics build: " +
                                 (nativeIsX64 ? "x64" : "x86"));
                return;
            }

            var agxDynamicsPath = AGXUnity.IO.Environment.AGXDynamicsPath;

            if (string.IsNullOrEmpty(agxDynamicsPath))
            {
                Debug.LogWarning(GUI.AddColorTag("Copy AGX Dynamics binaries - unable to find AGX Dynamics directory.",
                                                 Color.red));
                return;
            }

            var agxPluginPath = AGXUnity.IO.Environment.Get(AGXUnity.IO.Environment.Variable.AGX_PLUGIN_PATH);

            if (string.IsNullOrEmpty(agxPluginPath))
            {
                Debug.LogWarning(GUI.AddColorTag("Copy AGX Dynamics binaries - unable to find AGX_PLUGIN_PATH.", Color.red));
                return;
            }

            var targetExecutableFileInfo = new FileInfo(targetPathFilename);

            if (!targetExecutableFileInfo.Exists)
            {
                Debug.LogWarning(GUI.AddColorTag("Target executable doesn't exist: ", Color.red) + targetPathFilename);
                return;
            }

            // Application.dataPath is 'Assets' folder here in Editor but
            // Application.dataPath is '<name>_Data' in the Player. We're
            // explicitly constructing '<name>_Data' here.
            var targetDataPath = targetExecutableFileInfo.Directory.FullName +
                                 Path.DirectorySeparatorChar +
                                 Path.GetFileNameWithoutExtension(targetExecutableFileInfo.Name) +
                                 "_Data";


            if (IO.Utils.AGXDynamicsInstalledInProject)
            {
                PostBuildInternal(agxDynamicsPath,
                                  agxPluginPath,
                                  targetExecutableFileInfo,
                                  targetDataPath);
            }
            else
            {
                PostBuildExternal(agxDynamicsPath,
                                  agxPluginPath,
                                  targetExecutableFileInfo,
                                  targetDataPath);
            }
        }
Пример #33
0
    /// <summary>
    /// 分析资源
    /// </summary>
    /// <param name="paths"></param>
    /// <param name="target"></param>
    /// <param name="outpath"></param>
    private static void AnalyzeResource(string[] paths, BuildTarget target, string outpath)
    {
        curManifestConfig = new ManifestConfig();
        //加载存在的配置
        ManifestConfig lastManifestConfig = null;
        var            lastConfigPath     = IPath.Combine(outpath, "Art/Config.json");

        if (File.Exists(lastConfigPath))
        {
            lastManifestConfig = new ManifestConfig(File.ReadAllText(lastConfigPath));
        }
        else
        {
            lastManifestConfig = new ManifestConfig();
        }

        List <string> changeList = new List <string>();
        float         curIndex   = 0;

        foreach (var path in paths)
        {
            var _path = path.Replace("\\", "/");

            EditorUtility.DisplayProgressBar("分析资源 -" + target.ToString(),
                                             "分析:" + Path.GetFileNameWithoutExtension(_path) + "   进度:" + curIndex + "/" + paths.Length,
                                             curIndex / paths.Length);
            curIndex++;
            //获取被依赖的路径
            var dependsource         = "Assets" + _path.Replace(Application.dataPath, "");
            var allDependObjectPaths = AssetDatabase.GetDependencies(dependsource).ToList();

            var UIID = GetMD5HashFromFile(_path);
            if (string.IsNullOrEmpty(UIID))
            {
                continue;
            }


            List <string> dependAssets = new List <string>();
            //处理依赖资源是否打包
            for (int i = 0; i < allDependObjectPaths.Count; i++)
            {
                //
                var dependPath = allDependObjectPaths[i];


                //脚本不打包
                var ext = Path.GetExtension(dependPath).ToLower();
                if (ext == ".cs" || ext == ".js")
                {
                    continue;
                }

                //
                AssetImporter ai = AssetImporter.GetAtPath(dependPath);
                if (ai == null)
                {
                    BDebug.Log("not find Resource " + dependPath);
                    continue;
                }


                var dependObjPath = Application.dataPath + dependPath.TrimStart("Assets".ToCharArray());

                var uiid = GetMD5HashFromFile(dependObjPath);
                if (string.IsNullOrEmpty(uiid))
                {
                    continue;
                }

                string abname = "assets" + dependObjPath.Replace(Application.dataPath, "").ToLower();

                ManifestItem manifestItem = null;
                lastManifestConfig.Manifest.TryGetValue(abname, out manifestItem);
                //last没有或者 uiid不一致被改动,
                if (manifestItem == null || manifestItem.UIID != uiid)
                {
                    ai.assetBundleName    = abname;
                    ai.assetBundleVariant = "";

                    changeList.Add(abname);
                }
                else
                {
                    ai.assetBundleName = null;
                }

                //被依赖的文件,不保存其依赖信息
                if (abname != dependsource.ToLower()) //依赖列表中会包含自己
                {
                    curManifestConfig.AddDepend(abname, uiid, new List <string>());
                }

                dependAssets.Add(abname);
            }


            //保存主文件的依赖
            if (dependAssets.Count > 0)
            {
                dependAssets.Remove(dependsource.ToLower());
                curManifestConfig.AddDepend(dependsource.ToLower(), UIID, dependAssets);
            }
        }



        EditorUtility.ClearProgressBar();
        Debug.Log("本地需要打包资源:" + changeList.Count);
    }
Пример #34
0
 static string GetBuildPath(BuildTarget target, string buildName)
 {
     return("Builds/" + target.ToString() + "/" + GetLongBuildName(target, buildName));
 }
Пример #35
0
 static string GetLongBuildName(BuildTarget target, string buildName)
 {
     return(Application.productName + "_" + target.ToString() + "_" + buildName);
 }
Пример #36
0
    /// <summary>
    /// Build AssetBundle
    /// </summary>
    /// <param name="target"></param>
    static void PackAssetBundle(BuildTarget target)
    {
        Object[] objs = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        if (objs.Length <= 0)
        {
            return;
        }

        string resourcePath = Application.dataPath + "/Resources";

        if (!Directory.Exists(resourcePath))
        {
            Directory.CreateDirectory(resourcePath);
        }

        string savePath = EditorUtility.SaveFolderPanel("Save Folder", resourcePath, "");

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

        AssetBundleBuild[] assetBundle = new AssetBundleBuild[1];
        string[]           assetNames  = new string[objs.Length];
        for (int i = 0; i < objs.Length; i++)
        {
            assetNames[i] = AssetDatabase.GetAssetPath(objs[i]);
        }
        string fileName = objs[0].name + "_" + target.ToString() + ".unity3d";

        assetBundle[0] = new AssetBundleBuild()
        {
            assetBundleName = fileName,
            assetNames      = assetNames
        };

        BuildPipeline.BuildAssetBundles(savePath, assetBundle,
                                        BuildAssetBundleOptions.UncompressedAssetBundle, target);

        #region ΢С¹¤×÷
        if (File.Exists(savePath + "/" + fileName + ".manifest"))
        {
            File.Delete(savePath + "/" + fileName + ".manifest");
        }
        string[] filepathInfo = savePath.Split('/');
        string   flodName     = filepathInfo[filepathInfo.Length - 1];
        if (File.Exists(savePath + "/" + flodName))
        {
            File.Delete(savePath + "/" + flodName);
        }
        if (File.Exists(savePath + "/" + flodName + ".manifest"))
        {
            File.Delete(savePath + "/" + flodName + ".manifest");
        }
        #endregion

        if (File.Exists(savePath + "/" + fileName))
        {
            EditorUtility.OpenWithDefaultApp(savePath);
        }
    }
 private static string GetAssetBundleDirectoryName(BuildTarget buildTarget)
 {
     return(buildTarget.ToString());
 }
Пример #38
0
 static string GetOutPutPath(BuildTarget buildTarget)
 {
     return(Path.Combine(outPath, buildTarget.ToString()));// outPath + "/" + buildTarget.ToString();
 }
Пример #39
0
        public static void OnPostprocessiOSBuild(BuildTarget target, string iBuiltProjectPath)
        {
            UtilsLog.Info("PostProcessor",
                          "OnPostprocessiOSBuild()::Target:{0} ProPath:{1}", target.ToString(), iBuiltProjectPath);
#if UNITY_EDITOR
            if (target != BuildTarget.iOS)
            {
                return;
            }

            const string funcBlock = "PostProcessor.OnPostprocessiOSBuild()";
            BuildLogger.OpenBlock(funcBlock);

            const string  TargetProjectName = "Unity-iPhone";
            BuildSettings _buildSetting     = BuildSettings.GetInstance(BuildSettings.AssetFileDir);
            if (null == _buildSetting)
            {
                return;
            }
            // 取得设定情报列表
            XCSettingItem[] settings = _buildSetting.GetXCSettingInfo(TargetProjectName);
            if ((settings == null) || (settings.Length <= 0))
            {
                BuildLogger.CloseBlock();
                return;
            }

            string     pbxprojPath = PBXProject.GetPBXProjectPath(iBuiltProjectPath);
            PBXProject project     = new PBXProject();
            project.ReadFromString(File.ReadAllText(pbxprojPath));
            string targetGUID = project.TargetGuidByName(TargetProjectName);

            // BuildMode(debug/release/store)
            string debugConfigGUID   = project.BuildConfigByName(targetGUID, "Debug");
            string releaseConfigGUID = project.BuildConfigByName(targetGUID, "Release");

            foreach (XCSettingItem item in settings)
            {
                switch (item.Type)
                {
                case TXCSettingInfoType.ReplaceSource:
                {
                    foreach (string value in item.Value.LValue)
                    {
                        ReplaceSource(iBuiltProjectPath, value);
                        BuildLogger.LogMessage("Replace Source {0} -> {1}", value, iBuiltProjectPath);
                    }
                }
                break;

                case TXCSettingInfoType.FrameWorks:
                {
                    foreach (string frameWork in item.Value.LValue)
                    {
#if UNITY_2017_1_OR_NEWER
                        if (project.ContainsFramework(targetGUID, frameWork) == false)
                        {
#else
                        if (project.HasFramework(frameWork) == false)
                        {
#endif
                            project.AddFrameworkToProject(targetGUID, frameWork, false);
                            BuildLogger.LogMessage("Add FrameWork -> {0}", frameWork);
                        }
                    }
                }
                break;

                case TXCSettingInfoType.Libraries:
                {
                    foreach (string library in item.Value.LValue)
                    {
                        string fileGuid = project.AddFile("usr/lib/" + library, "Frameworks/" + library, PBXSourceTree.Sdk);
                        project.AddFileToBuild(targetGUID, fileGuid);
                        BuildLogger.LogMessage("Add Library -> {0}", library);
                    }
                }
                break;

                case TXCSettingInfoType.IncludeFiles:
                {
                    foreach (string file in item.Value.LValue)
                    {
                        string addFilePath = null;
                        PreSetFileToProject(iBuiltProjectPath, file, ref addFilePath);

                        if (string.IsNullOrEmpty(addFilePath) == false)
                        {
                            string fileGUID = project.AddFile(addFilePath, addFilePath, PBXSourceTree.Source);
                            project.AddFileToBuild(targetGUID, fileGUID);

                            BuildLogger.LogMessage("Add File -> {0}", file);
                        }
                    }
                }
                break;

                case TXCSettingInfoType.IncludeFolders:
                {
                    foreach (string folder in item.Value.LValue)
                    {
                        string copyTo          = null;
                        string addDirReference = null;

                        PreSetFolderToProject(iBuiltProjectPath, folder, ref copyTo, ref addDirReference);
                        if ((string.IsNullOrEmpty(copyTo) == false) &&
                            (string.IsNullOrEmpty(addDirReference) == false))
                        {
                            project.AddFolderReference(copyTo, addDirReference, PBXSourceTree.Source);
                            BuildLogger.LogMessage("Add Folder -> {0}", folder);
                        }
                    }
                }
                break;

                case TXCSettingInfoType.Bool:
                {
                    // Debug
                    if (TXCBool.Yes == item.Debug.BValue)
                    {
                        project.SetBuildPropertyForConfig(debugConfigGUID, item.Key, "YES");
                    }
                    else
                    {
                        project.SetBuildPropertyForConfig(debugConfigGUID, item.Key, "NO");
                    }

                    BuildLogger.LogMessage("Add Bool(Debug) -> Key:{0} Value:{1}", item.Key, item.Debug.BValue.ToString());

                    // Release
                    if (TXCBool.Yes == item.Release.BValue)
                    {
                        project.SetBuildPropertyForConfig(releaseConfigGUID, item.Key, "YES");
                    }
                    else
                    {
                        project.SetBuildPropertyForConfig(releaseConfigGUID, item.Key, "NO");
                    }

                    BuildLogger.LogMessage("Add Bool(Release) -> Key:{0} Value:{1}", item.Key, item.Release.BValue.ToString());
                }
                break;

                case TXCSettingInfoType.String:
                {
                    // Debug
                    project.SetBuildPropertyForConfig(debugConfigGUID, item.Key, item.Debug.SValue);

                    BuildLogger.LogMessage("Add String(Debug) -> Key:{0} Value:{1}", item.Key, item.Debug.SValue);

                    // Release
                    project.SetBuildPropertyForConfig(releaseConfigGUID, item.Key, item.Release.SValue);

                    BuildLogger.LogMessage("Add String(Release) -> Key:{0} Value:{1}", item.Key, item.Release.SValue);
                }
                break;

                case TXCSettingInfoType.List:
                {
                    // Debug
                    foreach (string value in item.Debug.LValue)
                    {
                        project.AddBuildPropertyForConfig(debugConfigGUID, item.Key, value);

                        BuildLogger.LogMessage("Add List(Debug) -> Key:{0} Item:{1}", item.Key, value);
                    }
                    // Release
                    foreach (string value in item.Release.LValue)
                    {
                        project.AddBuildPropertyForConfig(releaseConfigGUID, item.Key, value);

                        BuildLogger.LogMessage("Add List(Release) -> Key:{0} Item:{1}", item.Key, value);
                    }
                }
                break;

                default:
                    break;
                }
            }

            File.WriteAllText(pbxprojPath, project.WriteToString());
            BuildLogger.CloseBlock();
#endif
        }
        private void BuildAssetBundles(AssetBundleBuild[] buildMap, BuildAssetBundleOptions buildOptions, BuildTarget buildTarget)
        {
            m_BuildReport.LogInfo("Start build AssetBundles for '{0}'...", buildTarget.ToString());

            string buildTargetUrlName = GetBuildTargetName(buildTarget);

            string workingPath = string.Format("{0}{1}/", WorkingPath, buildTargetUrlName);

            m_BuildReport.LogInfo("Working path is '{0}'.", workingPath);

            string outputPackagePath = string.Format("{0}{1}/", OutputPackagePath, buildTargetUrlName);

            Directory.CreateDirectory(outputPackagePath);
            m_BuildReport.LogInfo("Output package path is '{0}'.", outputPackagePath);

            string outputZipPath = string.Format("{0}{1}/", OutputZipPath, buildTargetUrlName);

            Directory.CreateDirectory(outputZipPath);
            m_BuildReport.LogInfo("output Zip Path is '{0}'.", outputZipPath);

            // Clean working path
            List <string> validNames = new List <string>();

            foreach (AssetBundleBuild i in buildMap)
            {
                string assetBundleName = GetAssetBundleFullName(i.assetBundleName, i.assetBundleVariant);
                validNames.Add(assetBundleName);
            }

            if (Directory.Exists(workingPath))
            {
                Uri      workingUri = new Uri(workingPath, UriKind.RelativeOrAbsolute);
                string[] fileNames  = Directory.GetFiles(workingPath, "*", SearchOption.AllDirectories);
                foreach (string fileName in fileNames)
                {
                    if (fileName.EndsWith(".manifest"))
                    {
                        continue;
                    }

                    string relativeName = workingUri.MakeRelativeUri(new Uri(fileName)).ToString();
                    if (!validNames.Contains(relativeName))
                    {
                        File.Delete(fileName);
                    }
                }

                string[] manifestNames = Directory.GetFiles(workingPath, "*.manifest", SearchOption.AllDirectories);
                foreach (string manifestName in manifestNames)
                {
                    if (!File.Exists(manifestName.Substring(0, manifestName.LastIndexOf('.'))))
                    {
                        File.Delete(manifestName);
                    }
                }

                Icarus.GameFramework.Utility.Path.RemoveEmptyDirectory(workingPath);
            }

            if (!Directory.Exists(workingPath))
            {
                Directory.CreateDirectory(workingPath);
            }

            if (m_BuildEventHandler != null)
            {
                m_BuildReport.LogInfo("Execute build event handler 'PreProcessBuild' for '{0}'...", buildTarget.ToString());
                m_BuildEventHandler.PreProcessBuild(buildTarget, workingPath, outputPackagePath, outputZipPath);
            }

            // Build AssetBundles
            m_BuildReport.LogInfo("Unity start build AssetBundles for '{0}'...", buildTarget.ToString());
            AssetBundleManifest assetBundleManifest = BuildPipeline.BuildAssetBundles(workingPath, buildMap, buildOptions, buildTarget);

            if (assetBundleManifest == null)
            {
                m_BuildReport.LogError("Build AssetBundles for '{0}' failure.", buildTarget.ToString());
                return;
            }

            m_BuildReport.LogInfo("Unity build AssetBundles for '{0}' complete.", buildTarget.ToString());

            // Process AssetBundles
            for (int i = 0; i < buildMap.Length; i++)
            {
                string assetBundleFullName = GetAssetBundleFullName(buildMap[i].assetBundleName, buildMap[i].assetBundleVariant);
                if (ProcessingAssetBundle != null)
                {
                    if (ProcessingAssetBundle(assetBundleFullName, (float)(i + 1) / buildMap.Length))
                    {
                        m_BuildReport.LogWarning("The build has been canceled by user.");
                        return;
                    }
                }

                m_BuildReport.LogInfo("Start process '{0}' for '{1}'...", assetBundleFullName, buildTarget.ToString());

                ProcessAssetBundle(workingPath, outputPackagePath, outputZipPath, buildTarget, buildMap[i].assetBundleName, buildMap[i].assetBundleVariant);

                m_BuildReport.LogInfo("Process '{0}' for '{1}' complete.", assetBundleFullName, buildTarget.ToString());
            }

            //写入version.info
            _writeVersionInfoFile(outputZipPath);

            ProcessPackageList(outputPackagePath, buildTarget);
            m_BuildReport.LogInfo("Process package list for '{0}' complete.", buildTarget.ToString());

            if (m_BuildEventHandler != null)
            {
                m_BuildReport.LogInfo("Execute build event handler 'PostProcessBuild' for '{0}'...", buildTarget.ToString());
                m_BuildEventHandler.PostProcessBuild(buildTarget, workingPath, outputPackagePath, outputZipPath);
            }

            if (ProcessAssetBundleComplete != null)
            {
                ProcessAssetBundleComplete(buildTarget, "", 0, 0, 0, 0);
            }

            m_BuildReport.LogInfo("Build AssetBundles for '{0}' success.", buildTarget.ToString());
        }
Пример #41
0
    public static void BuildSceneBundles(string path, string streamPath, BuildTarget target)
    {
        // string path = "Assets/AssetBundleRes/scene/navmesh";
        string[] file_paths = Directory.GetFiles(path);
        // List<string> levels = new List<string>();
        foreach (string file_path in file_paths)
        {
            string ext = Path.GetExtension(file_path);
            if (ext.Equals(".unity"))
            {
                string navmesh_scene_name = Path.GetFileNameWithoutExtension(file_path);
                // levels.Add(file_path);
                string[] levels = new string[] { file_path };
                Debug.Log("file : " + file_path + " save : " + streamPath + "/" + navmesh_scene_name + " target:" + target.ToString());

                BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
                buildPlayerOptions.scenes           = new string[] { file_path };
                buildPlayerOptions.locationPathName = streamPath + "/" + navmesh_scene_name;
                buildPlayerOptions.target           = target;
                buildPlayerOptions.options          = BuildOptions.BuildAdditionalStreamedScenes;

                UnityEditor.Build.Reporting.BuildReport  report  = BuildPipeline.BuildPlayer(buildPlayerOptions);
                UnityEditor.Build.Reporting.BuildSummary summary = report.summary;
                if (summary.result == UnityEditor.Build.Reporting.BuildResult.Succeeded)
                {
                    Debug.Log("Build scene succeeded: " + summary.totalSize + " bytes");
                }

                if (summary.result == UnityEditor.Build.Reporting.BuildResult.Failed)
                {
                    Debug.Log("Build scene failed : " + file_path);
                }
                // BuildPipeline.BuildPlayer(levels, streamPath+"/"+navmesh_scene_name, target, BuildOptions.BuildAdditionalStreamedScenes);
            }
        }
    }
Пример #42
0
        /// <summary>
        /// Builds the release for the current platform
        /// </summary>
        public static void BuildRelease()
        {
            BuildTarget buildPlatform = EditorUserBuildSettings.activeBuildTarget;

            string releasePath = Directory.GetCurrentDirectory().Replace('\\', '/') + "/obj/";
            string buildPath   = Directory.GetCurrentDirectory().Replace('\\', '/') + "/bin/";

            switch (buildPlatform)
            {
            case BuildTarget.StandaloneWindows:
                releasePath += buildPlatform.ToString() + "/Installer/Installer.exe";
                buildPath   += buildPlatform.ToString() + "/Release/mistoftime_" + buildPlatform.ToString().ToLower() + ".exe";
                break;

            case BuildTarget.StandaloneWindows64:
                releasePath += buildPlatform.ToString() + "/Installer/Installer.exe";
                buildPath   += buildPlatform.ToString() + "/Release/mistoftime_" + buildPlatform.ToString().ToLower() + ".exe";
                break;

            case BuildTarget.Android:
                releasePath += buildPlatform.ToString() + "/Player/motboot.apk";
                buildPath   += buildPlatform.ToString() + "/Release/mistoftime_" + buildPlatform.ToString().ToLower() + ".apk";
                break;

            case BuildTarget.WebGL:
                releasePath += buildPlatform.ToString() + "/Launcher/Launcher.html";
                buildPath   += buildPlatform.ToString() + "/Release/mistoftime_" + buildPlatform.ToString().ToLower() + ".html";
                break;

            default:
                Debug.LogError("Mist of Time does not support " + buildPlatform.ToString() + " as a build target");
                return;
            }

            if (Directory.Exists(Path.GetDirectoryName(buildPath)))
            {
                Directory.Delete(Path.GetDirectoryName(buildPath), true);
            }

            Directory.CreateDirectory(Path.GetDirectoryName(buildPath));

            if (buildPlatform == BuildTarget.StandaloneWindows ||
                buildPlatform == BuildTarget.StandaloneWindows64 ||
                buildPlatform == BuildTarget.Android)
            {
                BuildPlayer();
            }

            if (buildPlatform == BuildTarget.StandaloneWindows ||
                buildPlatform == BuildTarget.StandaloneWindows64)
            {
                System.Diagnostics.Process installerCMD = new System.Diagnostics.Process();
                installerCMD.StartInfo.FileName         = Directory.GetCurrentDirectory().Replace("\\", "/") + "/Assets/PlayerAssets/Standalone/" + buildPlatform.ToString() + "/Installer/build.bat";
                installerCMD.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory().Replace("\\", "/") + "/Assets/PlayerAssets/Standalone/" + buildPlatform.ToString() + "/Installer";
                installerCMD.StartInfo.UseShellExecute  = false;
                installerCMD.StartInfo.CreateNoWindow   = true;
                installerCMD.Start();
                EditorUtility.DisplayProgressBar("Building Installer", "Building Installer.exe", 0.25f);
                installerCMD.WaitForExit();
                EditorUtility.ClearProgressBar();

                if (!File.Exists(releasePath))
                {
                    Debug.LogError("Installer failed to build!");
                    return;
                }
            }

            if (buildPlatform == BuildTarget.WebGL)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(releasePath));
                File.WriteAllText(releasePath, "<meta http-equiv=\"refresh\" content=\"0; url=../Patch/motboot/index.html\" />");
            }

            File.Copy(releasePath, buildPath);
        }
Пример #43
0
        /// <summary>
        /// Builds a patch for the current platform
        /// </summary>
        public static void BuildPatch()
        {
            BuildTarget buildPlatform = EditorUserBuildSettings.activeBuildTarget;

            string playerPath       = Directory.GetCurrentDirectory().Replace('\\', '/') + "/obj/";
            string assetBundlesPath = Directory.GetCurrentDirectory().Replace('\\', '/') + "/obj/";
            string buildPath        = Directory.GetCurrentDirectory().Replace('\\', '/') + "/bin/";

            switch (buildPlatform)
            {
            case BuildTarget.StandaloneWindows:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            case BuildTarget.StandaloneWindows64:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            case BuildTarget.Android:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            case BuildTarget.WebGL:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            default:
                Debug.LogError("Mist of Time does not support " + buildPlatform.ToString() + " as a build target");
                return;
            }

            if (Directory.Exists(Path.GetDirectoryName(buildPath)))
            {
                Directory.Delete(Path.GetDirectoryName(buildPath), true);
            }

            Directory.CreateDirectory(Path.GetDirectoryName(buildPath));

            BuildPlayer();
            BuildAssetBundles();

            CopyDirectory(playerPath, buildPath, new string[] { });
            CopyDirectory(assetBundlesPath, buildPath, new string[] { ".manifest" });

            File.Move(buildPath + "AssetBundles", buildPath + "FTABLE.DAT");

            PatchInfo newPatchInfo = new PatchInfo();

            string[] buildDirectories = Directory.GetDirectories(buildPath, "*", SearchOption.AllDirectories);

            for (int i = 0; i < buildDirectories.Length; i++)
            {
                buildDirectories[i] = buildDirectories[i].Replace('\\', '/').Replace(buildPath, "");
                EditorUtility.DisplayProgressBar("Generating Patch Info", "Processing " + buildDirectories[i], ((float)i / buildDirectories.Length));
                newPatchInfo.PatchDirectories.Add(new PatchInfoDirectory(buildDirectories[i]));
            }

            EditorUtility.ClearProgressBar();

            string[] buildFiles = Directory.GetFiles(buildPath, "*", SearchOption.AllDirectories);

            for (int i = 0; i < buildFiles.Length; i++)
            {
                buildFiles[i] = buildFiles[i].Replace('\\', '/').Replace(buildPath, "");
                EditorUtility.DisplayProgressBar("Generating Patch Info", "Processing " + buildFiles[i], ((float)i / buildFiles.Length));

                using (FileStream stream = File.OpenRead(buildPath + buildFiles[i]))
                {
                    SHA256Managed sha      = new SHA256Managed();
                    byte[]        checksum = sha.ComputeHash(stream);
                    newPatchInfo.PatchFiles.Add(new PatchInfoFile(buildFiles[i], stream.Length, BitConverter.ToString(checksum).Replace("-", string.Empty)));
                }
            }

            EditorUtility.ClearProgressBar();

            newPatchInfo.Serialize(buildPath + "patch.txt");

            VersionInfo currentVersionInfo = (VersionInfo)AssetDatabase.LoadAssetAtPath("Assets/MOT/VersionInfo.asset", typeof(VersionInfo));

            File.WriteAllText(buildPath + "patch.ver", currentVersionInfo.PatchVersion);
        }
Пример #44
0
        public void ParseCommandLineArgs_SucceedsWithSeparateArgs_UnitTest()
        {
            string[] testArgs = { "-token", testAccessToken, "-outputDir", testOutputDir, "-testPlatform", testPlatform.ToString(), "-projectId", testProjectId };

            var commandLineArgs = CloudTestBuilder.ParseCommandLineArgs(testArgs);

            Assert.AreEqual(commandLineArgs.AccessToken, testAccessToken);
            Assert.AreEqual(commandLineArgs.TargetPlatform, testPlatform);
            Assert.AreEqual(CloudTestConfig.BuildFolder, testOutputDir);
        }
Пример #45
0
 internal static string GetPath(BuildTarget target)
 {
     return("ProjectSettings/BurstAotSettings_" + target.ToString() + ".json");
 }
Пример #46
0
    // ------------------------------------------------------------------------
    // e.g. BuildTargetGroup.Standalone, BuildTarget.StandaloneOSX
    // ------------------------------------------------------------------------
    private static void BuildProject(string[] scenes, string targetDir, BuildTargetGroup buildTargetGroup, BuildTarget buildTarget, BuildOptions buildOptions)
    {
        PlayerSettings.keyaliasPass = "******";
        PlayerSettings.keystorePass = "******";

        System.Console.WriteLine("[JenkinsBuild] Building:" + targetDir + " buildTargetGroup:" + buildTargetGroup.ToString() + " buildTarget:" + buildTarget.ToString());

        // https://docs.unity3d.com/ScriptReference/EditorUserBuildSettings.SwitchActiveBuildTarget.html
        bool switchResult = EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildTarget);

        if (switchResult)
        {
            System.Console.WriteLine("[JenkinsBuild] Successfully changed Build Target to: " + buildTarget.ToString());
        }
        else
        {
            System.Console.WriteLine("[JenkinsBuild] Unable to change Build Target to: " + buildTarget.ToString() + " Exiting...");
            return;
        }

        // https://docs.unity3d.com/ScriptReference/BuildPipeline.BuildPlayer.html
        BuildReport  buildReport  = BuildPipeline.BuildPlayer(scenes, targetDir, buildTarget, buildOptions);
        BuildSummary buildSummary = buildReport.summary;

        if (buildSummary.result == BuildResult.Succeeded)
        {
            System.Console.WriteLine("[JenkinsBuild] Build Success: Time:" + buildSummary.totalTime + " Size:" + buildSummary.totalSize + " bytes");
        }
        else
        {
            System.Console.WriteLine("[JenkinsBuild] Build Failed: Time:" + buildSummary.totalTime + " Total Errors:" + buildSummary.totalErrors);
        }
    }
Пример #47
0
        private static void OnPostProcessBuild(BuildTarget target, string pathToBuildProject)
        {
            Log.Info("项目发布成功!发布平台:" + target.ToString() + "!发布路径:" + pathToBuildProject + "!");

            PostProcessBuildEvent?.Invoke(target, pathToBuildProject);
        }
        public override string CalculateFinalPluginPath(string platformName, PluginImporter imp)
        {
            BuildTarget buildTargetByName = BuildPipeline.GetBuildTargetByName(platformName);
            bool        flag  = buildTargetByName == BuildTarget.StandaloneWindows || buildTargetByName == BuildTarget.StandaloneWindows64;
            bool        flag2 = buildTargetByName == BuildTarget.StandaloneOSXIntel || buildTargetByName == BuildTarget.StandaloneOSXIntel64 || buildTargetByName == BuildTarget.StandaloneOSXUniversal;
            bool        flag3 = buildTargetByName == BuildTarget.StandaloneLinux || buildTargetByName == BuildTarget.StandaloneLinux64 || buildTargetByName == BuildTarget.StandaloneLinuxUniversal;

            if (!flag3 && !flag2 && !flag)
            {
                throw new Exception(string.Format("Failed to resolve standalone platform, platform string '{0}', resolved target '{1}'", platformName, buildTargetByName.ToString()));
            }
            if (flag && !this.IsUsableOnWindows(imp))
            {
                return(string.Empty);
            }
            if (flag2 && !this.IsUsableOnOSX(imp))
            {
                return(string.Empty);
            }
            if (flag3 && !this.IsUsableOnLinux(imp))
            {
                return(string.Empty);
            }
            string platformData = imp.GetPlatformData(platformName, "CPU");

            if (string.Compare(platformData, "None", true) == 0)
            {
                return(string.Empty);
            }
            if (!string.IsNullOrEmpty(platformData) && string.Compare(platformData, "AnyCPU", true) != 0)
            {
                return(Path.Combine(platformData, Path.GetFileName(imp.assetPath)));
            }
            return(Path.GetFileName(imp.assetPath));
        }
Пример #49
0
 public static string GetPathSafeTargetName(BuildTarget t)
 {
     return(t.ToString());
 }
Пример #50
0
    static void BuildAssetBundles(BuildTarget platform)
    {
        string path = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Assets/AssetBundles/" + platform.ToString());

        if (System.IO.Directory.Exists(path) == false)
        {
            System.IO.Directory.CreateDirectory(path);
            Debug.LogFormat("creating directory {0}", path);
        }

        BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.ChunkBasedCompression, platform);
    }
Пример #51
0
 public virtual string GetPlatformOutput(string outputPath, BuildTarget buildTarget)
 {
     return(System.IO.Path.Combine(outputPath, buildTarget.ToString()).Replace(@"\", "/"));
 }
Пример #52
0
		internal static void ExecuteSelectedPolicy(BuildTarget target, int[] textureImporterInstanceIDs)
		{
			Packer.RegenerateList();
			Analytics.Event("SpritePacker", "ExecuteSelectedPolicy", target.ToString(), textureImporterInstanceIDs.Length);
			Type type = Packer.m_policyTypeCache[Packer.m_selectedPolicy];
			IPackerPolicy packerPolicy = Activator.CreateInstance(type) as IPackerPolicy;
			packerPolicy.OnGroupAtlases(target, new PackerJob(), textureImporterInstanceIDs);
		}
Пример #53
0
        /// <summary>
        /// 分析资源
        /// </summary>
        /// <param name="paths"></param>
        /// <param name="target"></param>
        /// <param name="outpath"></param>
        private static void AnalyzeResource(string[] paths, BuildTarget target, string outpath)
        {
            additionBuildPackageCache = new List <string>();
            CurManifestConfig         = new ManifestConfig();
            //以下三个建议使用内部函数,不要直接调用unity原生接口获取,
            allfileHashMap  = new Dictionary <string, string>();         //file hash获取缓存
            assetImpoterMap = new Dictionary <string, AssetImporter>();  //Assetimport获取缓存
            DependenciesMap = new Dictionary <string, List <string> >(); //依赖获取缓存

            //加载配置
            ManifestConfig lastManifestConfig = null;

            if (File.Exists(configPath))
            {
                lastManifestConfig = new ManifestConfig(File.ReadAllText(configPath));
            }
            else
            {
                lastManifestConfig = new ManifestConfig();
            }
            //

            /***************************************开始分析资源****************************************/
            //1.收集图集信息
            EditorUtility.DisplayProgressBar("分析资源", "收集SpriteAtlas", 0);
            GetSpriteAtlasInfo();
            //2.收集单ab多资源信息
            GetBuildAbConfig();
            //3.开始分析资源
            bool          isAdditionBuild = allfileHashMap.Count > 0; //是否为增量打包
            List <string> changeList      = new List <string>();

            for (int index = 0; index < paths.Length; index++)
            {
                var mainAssetFullPath = paths[index].Replace("\\", "/");
                EditorUtility.DisplayProgressBar("分析资源",
                                                 string.Format("分析:{0} {1}/{2}", Path.GetFileName(mainAssetFullPath), index + 1, paths.Length),
                                                 (index + 1f) / paths.Length);
                //获取被依赖的路径
                var mainAssetPath = "Assets" + mainAssetFullPath.Replace(Application.dataPath, "");
                var subAssetsPath = GetDependencies(mainAssetPath).ToList();


                List <string> subAssetHashList = new List <string>();
                //处理依赖资源打包
                for (int i = 0; i < subAssetsPath.Count; i++)
                {
                    var    subAsset     = subAssetsPath[i];
                    var    subAssetPath = subAssetsPath[i];// Application.dataPath + subAsset.Replace("Assets/", "/");
                    string subAssetHash = GetHashFromFile(subAssetPath);
                    subAssetHashList.Add(subAssetHash);

                    //本地ab文件存在则不打包
                    var localABPath = IPath.Combine(outpath, subAssetHash);
                    if (File.Exists(localABPath))
                    {
                        var lastItem = lastManifestConfig.GetManifestItemByHash(subAssetHash);
                        if (lastItem != null)
                        {
                            CurManifestConfig.AddItem(lastItem);
                            continue;
                        }
                    }
                    else
                    {
                        // 需要对比之前的hash
                        var lastItem = lastManifestConfig.GetManifestItemByHash(subAssetHash);
                        if (lastItem != null && lastItem.Package != "" && lastItem.Hash == subAssetHash)
                        {
                            CurManifestConfig.AddItem(lastItem);
                            continue;
                        }
                    }

                    #region 嵌套引用 - 缓存

                    var subAssetDpendList = GetDependencies(subAsset).ToList();
                    //sub dpend 2 hash
                    if (subAssetDpendList.Count > 1)
                    {
                        for (int j = 0; j < subAssetDpendList.Count; j++)
                        {
                            var sbd = subAssetDpendList[j];// Application.dataPath + subAssetDpendList[j].Replace("Assets/", "/");
                            subAssetDpendList[j] = GetHashFromFile(sbd);
                        }
                    }
                    else
                    {
                        subAssetDpendList.Clear();
                    }

                    #endregion

                    //开始设置abname
                    var ai = GetAssetImporter(subAsset);

                    ManifestItem.AssetTypeEnum @enum = ManifestItem.AssetTypeEnum.Others;
                    var    savename        = CheckAssetSaveInfo(subAsset, ref @enum);
                    string packageHashName = null;


                    #region 单ab多资源模式

                    if (IsMakePackage(subAsset, ref packageHashName))
                    {
                        #region 增量打包遇到单ab多资源

                        //增量打包时,如果遇到多包合一时,其中某个变动,剩余的也要一次性打出
//                        if (isAdditionBuild && !additionBuildPackageCache.Contains(packageHashName))
//                        {
//                            var lastAssets = lastManifestConfig.Manifest_NameKey.Values.ToList().FindAll((item) =>
//                                !string.IsNullOrEmpty(item.Package) && item.Package == packageHashName);
//                            foreach (var la in lastAssets)
//                            {
//                                //考虑增量打包时候,得补齐Runtime下的路径名
//                                var path = la.Name;
//                                if (!path.StartsWith("Assets/"))
//                                {
//                                    foreach (var key in LastAllAssetCache.Keys)
//                                    {
//                                        var p = path + ".";
//                                        if (key.Contains(p))
//                                        {
//                                            path = key;
//                                        }
//                                    }
//                                }
//
//                                //获取上次的importer
//                                var laAI = GetAssetImporter(path);
//                                if (laAI == null)
//                                {
//                                    Debug.LogError("资源不存在:" + la.Name);
//                                    continue;
//                                }
//
//                                laAI.assetBundleName = packageHashName;
//                                laAI.assetBundleVariant = "";
//                            }
//
//                            if (isAdditionBuild)
//                            {
//                                additionBuildPackageCache.Add(packageHashName);
//                            }
//                        }

                        #endregion


                        string packageName = "";
                        foreach (var item in allfileHashMap)
                        {
                            if (item.Value == packageHashName)
                            {
                                packageName = item.Key;
                                packageName = packageName.Replace(BApplication.projroot + "/", "");
                                break;
                            }
                        }


                        //保存配置
                        if (subAsset != mainAssetPath)
                        {
                            CurManifestConfig.AddItem(savename, subAssetHash, subAssetDpendList, @enum,
                                                      packageHashName);
                        }

                        ai.assetBundleName    = packageName;
                        ai.assetBundleVariant = "";

//                        ai.assetBundleName = packageHashName;
//                        ai.assetBundleVariant = "";
                    }

                    #endregion

                    #region 单ab单资源模式

                    else
                    {
                        if (subAsset != mainAssetPath)
                        {
                            CurManifestConfig.AddItem(savename, subAssetHash, subAssetDpendList, @enum);
                        }

//                        if (!subAsset.Contains("Assets/"))
//                        {
//                            ai.assetBundleName = "Assets/Resource/Runtime/" + savename;
//                            ai.assetBundleVariant = "";
//                        }
//                        else
//                        {
                        ai.assetBundleName    = subAsset;
                        ai.assetBundleVariant = "";
//                        }
//                        ai.assetBundleName = subAssetHash;
//                        ai.assetBundleVariant = "";
                    }

                    #endregion


                    changeList.Add(subAsset);
                }

                //最后保存主文件
                var    mainHash = GetHashFromFile(mainAssetPath);
                string package  = null;
                subAssetHashList.Remove(mainHash);
                if (IsMakePackage(mainAssetPath, ref package))
                {
                    //单ab包-多资源模式
                    ManifestItem.AssetTypeEnum @enum = ManifestItem.AssetTypeEnum.Others;
                    var sn = CheckAssetSaveInfo(mainAssetPath, ref @enum);
                    CurManifestConfig.AddItem(sn, mainHash, subAssetHashList, @enum, package);
                }
                else
                {
                    //单ab包-单资源模式
                    ManifestItem.AssetTypeEnum @enum = ManifestItem.AssetTypeEnum.Others;
                    var sn = CheckAssetSaveInfo(mainAssetPath, ref @enum);
                    CurManifestConfig.AddItem(sn, mainHash, subAssetHashList, @enum);
                }
            }

            //补全 [单ab多资源的配置],并将真正的hash传入
            foreach (var con in PackageConfig)
            {
                var hash = GetHashFromString(con.AssetBundleName); //多合一ab的hash是要有所有的依赖文件 hash,再hash一次
                CurManifestConfig.AddItem(con.AssetBundleName, hash, new List <string>(),
                                          ManifestItem.AssetTypeEnum.Others);
            }

            //最后检查配置
            foreach (var item in CurManifestConfig.Manifest_HashKey.Values)
            {
                for (int i = 0; i < item.Depend.Count; i++)
                {
                    var dHash = item.Depend[i];
                    //判断是否在runtime内
                    var dItem = CurManifestConfig.GetManifestItemByHash(dHash);

                    if (dItem != null)
                    {
                        if (!string.IsNullOrEmpty(dItem.Package))
                        {
                            //将非Runtime目录中的
                            item.Depend[i] = dItem.Package;
                        }
                    }
                    else
                    {
                        Debug.LogError("【资源遗失】没找到依赖项:" + dHash);
                        foreach (var v in allfileHashMap)
                        {
                            if (dHash == v.Value)
                            {
                                Debug.LogError("hash source file:" + v.Key);
                                break;
                            }
                        }
                    }
                }

                item.Depend.Remove(item.Hash);
                item.Depend = item.Depend.Distinct().ToList();
            }

            EditorUtility.ClearProgressBar();
            changeList = changeList.Distinct().ToList();
            Debug.LogFormat("<color=red>本地需要打包数量:{0}</color>", changeList.Count);
            var buildpath = string.Format("{0}/{1}_changelist.json", Application.streamingAssetsPath,
                                          target.ToString());
            File.WriteAllText(buildpath, JsonMapper.ToJson(changeList));
            Debug.Log("本地打包保存:" + buildpath);
        }
Пример #54
0
        static void PerformBuild(BuildTarget targetBuild, bool isDevelopment)
        {
            UnityEngine.Debug.Log("*****PerformBuild - Build target: " + targetBuild);

            //EditorUserBuildSettings.SwitchActiveBuildTarget(targetBuild);
            EditorUserBuildSettings.appendProject = true;
            EditorUserBuildSettings.allowDebugging = false;
            EditorUserBuildSettings.development = isDevelopment;

            if (targetBuild == BuildTarget.Android)
            {
                PlayerSettings.Android.keystorePass = "******";
                PlayerSettings.Android.keyaliasName = "foxpoker";
                PlayerSettings.Android.keyaliasPass = "******";
            }

            UnityEngine.Debug.Log("*****PerformBuild - Using the bundle id: " + PlayerSettings.bundleIdentifier);

            string buildTargetDirect = Application.dataPath.Replace("/Assets", string.Format("/Build/{0}", targetBuild.ToString().ToLower()));
            if (Directory.Exists(buildTargetDirect) == false)
                Directory.CreateDirectory(buildTargetDirect);

            string locationPath = string.Format("{0}/{1}", buildTargetDirect, "FoxPoker");
            if (targetBuild == BuildTarget.Android)
                locationPath += string.Format("_{0:yyyyMMddHHmm}.apk", DateTime.Now);
            else if (targetBuild == BuildTarget.StandaloneWindows || targetBuild == BuildTarget.StandaloneWindows64)
                locationPath += ".exe";
            else if (targetBuild == BuildTarget.StandaloneOSXIntel || targetBuild == BuildTarget.StandaloneOSXIntel64 || targetBuild == BuildTarget.StandaloneOSXUniversal)
                locationPath += ".app";

            UnityEngine.Debug.Log("*****PerformBuild - UNITY_BUILD_TARGET Use path: " + locationPath);

            string[] buildScenes = (from scene in EditorBuildSettings.scenes where scene.enabled select scene.path).ToArray();
            var result = BuildPipeline.BuildPlayer(buildScenes, locationPath, targetBuild,
                targetBuild == BuildTarget.iPhone ? BuildOptions.SymlinkLibraries | BuildOptions.Development | BuildOptions.None : BuildOptions.None
            );

            if (result.Length > 0)
                UnityEngine.Debug.LogError("*****PerformBuild - Result: " + result);

            OpenExplorer(buildTargetDirect);
        }
Пример #55
0
 private static string GetAssetBundlesBuildPath(BuildTarget buildTarget)
 {
     return(Path.Combine("AssetBundles", buildTarget.ToString()));
 }
Пример #56
0
 private void OnProcessAssetBundleComplete(BuildTarget buildTarget, string versionListPath, int versionListLength, int versionListHashCode, int versionListZipLength, int versionListZipHashCode)
 {
     EditorUtility.ClearProgressBar();
     Debug.Log(string.Format("Build AssetBundles for '{0}' complete, version list path is '{1}', length is '{2}', hash code is '{3}', zip length is '{4}', zip hash code is '{5}'.", buildTarget.ToString(), versionListPath, versionListLength.ToString(), versionListHashCode.ToString("X8"), versionListZipLength.ToString(), versionListZipHashCode.ToString("X8")));
 }
Пример #57
0
 public static string GetAssetBundleDir(string outputPath, BuildTarget buildTarget)
 {
     return($"{outputPath}{buildTarget.ToString()}/");
 }
Пример #58
0
 public override string ToString()
 {
     return(ObjectNames.NicifyVariableName(m_Target.ToString()));
 }
Пример #59
0
 static string GetOutPutPath(BuildTarget buildTarget)
 {
     return Path.Combine(outPath, buildTarget.ToString());// outPath + "/" + buildTarget.ToString();
 }
Пример #60
0
 static string GetBuildPath(BuildTarget target, string buildName)
 {
     return("Builds/" + target.ToString() + "/" + Application.productName + "_" + target.ToString() + "_" + buildName);
 }