Exemple #1
29
    public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
    {
        #if UNITY_IPHONE
        string projectPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";

        PBXProject project = new PBXProject();

        project.ReadFromString(File.ReadAllText(projectPath));

        // This is the project name that Unity generates for iOS, isn't editable until after post processing
        string target = project.TargetGuidByName(PBXProject.GetUnityTargetName());

        #if UNITY_5_0
        project.AddBuildProperty(target, "FRAMEWORK_SEARCH_PATHS", "$(PROJECT_DIR)/Frameworks/Plugins/iOS");
        #else
        CopyAndReplaceDirectory("Assets/Plugins/iOS/FiksuSDK.bundle", Path.Combine(path, "Frameworks/FiksuSDK.bundle"));
        project.AddFileToBuild(target, project.AddFile("Frameworks/FiksuSDK.bundle", "Frameworks/FiksuSDK.bundle", PBXSourceTree.Source));

        CopyAndReplaceDirectory("Assets/Plugins/iOS/FiksuSDK.framework", Path.Combine(path, "Frameworks/FiksuSDK.framework"));
        project.AddFileToBuild(target, project.AddFile("Frameworks/FiksuSDK.framework", "Frameworks/FiksuSDK.framework", PBXSourceTree.Source));

        project.SetBuildProperty(target, "FRAMEWORK_SEARCH_PATHS", "$(inherited)");
        project.AddBuildProperty(target, "FRAMEWORK_SEARCH_PATHS", "$(PROJECT_DIR)/Frameworks");
        #endif

        project.AddFrameworkToProject(target, "AdSupport.framework", true);
        project.AddFrameworkToProject(target, "StoreKit.framework", true);
        project.AddFrameworkToProject(target, "Security.framework", true);
        project.AddFrameworkToProject(target, "SystemConfiguration.framework", false);
        project.AddFrameworkToProject(target, "MessageUI.framework", false);

        File.WriteAllText(projectPath, project.WriteToString());
        #endif
    }
    static bool CheckProcceed(BuildTarget expectedTarget)
    {
        if(UnityEditorInternal.InternalEditorUtility.inBatchMode)
        {
            if(EditorUserBuildSettings.activeBuildTarget != expectedTarget)
            {
                UnityEngine.Debug.LogError("BuildScript: Error: Unexpected Build Target In batch Mode: "
                    + EditorUserBuildSettings.activeBuildTarget + " Expected: " + expectedTarget );
            }
            return true;
        }

        if(EditorUserBuildSettings.activeBuildTarget != expectedTarget)
        {
        //			if(EditorUtility.DisplayDialogComplex("Platform Warning", "Warning Wrong Platform!\nCurrent: "
        //				+ EditorUserBuildSettings.activeBuildTarget.ToString()
        //				+ "\nNew Target: " + expectedTarget.ToString(), "Switch Platform", "Cancel", null) == 0)
        //			{
        //				EditorUserBuildSettings.SwitchActiveBuildTarget(expectedTarget);
        //				AssetDatabase.Refresh();
        //				return true;
        //			}
            UnityEngine.Debug.LogError("Error platform,stop build");
            return false;
        }
        return true;
    }
    public static void OnPostProcessBuild(BuildTarget target, string path)
    {
        EveryplaySettings settings = (EveryplaySettings)Resources.Load(EveryplaySettingsEditor.settingsFile);

        if(settings != null) {
            if(settings.IsEnabled) {
                if(settings.IsValid) {
                    if(target == BuildTarget.iPhone) {
                        PostProcessBuild_iOS(path, settings.clientId);
                    }
                    else if(target == BuildTarget.Android) {
                        PostProcessBuild_Android(path, settings.clientId);
                    }
                }
                else {
                    Debug.LogError("Everyplay will be disabled because client id, client secret or redirect URI was not valid.");
                    if(target == BuildTarget.iPhone) {
                        SetEveryplayEnabledForTarget(BuildTargetGroup.iPhone, false);
                    }
                    else if(target == BuildTarget.Android) {
                        SetEveryplayEnabledForTarget(BuildTargetGroup.Android, false);
                    }
                }
            }
        }
    }
 public static void BuildComplete(BuildTarget target, string pathToBuiltProject)
 {
     if (Application.isPlaying) {
         return;
     }
     Generated = false;
 }
		public static void OnPostprocessBuild(BuildTarget buildTarget, string path) {
			
			if (buildTarget == BuildTarget.Android) {
				SendBuildEvent ();
			}
		
		}
    public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
    {
        // Figure out which architecture we're building for.
        int arch;
        if (target == BuildTarget.StandaloneWindows)
            arch = 32;
        else if (target == BuildTarget.StandaloneWindows64)
            arch = 64;
        else
            return;

        // Rename the target to a .bin file for the auto-patcher to find later.
        string autoPatcherPath = Application.dataPath + "/OVR/Editor/OculusUnityPatcher_" + arch.ToString() + ".exe";
        string targetPath = pathToBuiltProject.Replace(".exe", "_DirectToRift.exe");

        if (File.Exists(targetPath))
            File.Delete(targetPath);

        File.Copy(autoPatcherPath, targetPath);

        string appInfoPath = pathToBuiltProject.Replace(".exe", "_Data/OVRAppInfo");
        var file = new System.IO.StreamWriter(appInfoPath);
        file.Write(PlayerSettings.companyName + "\\" + PlayerSettings.productName);
        file.Dispose();
    }
Exemple #7
0
		public static void RunIntegrationTests ( BuildTarget? targetPlatform, List<string> sceneList )
		{
			if (targetPlatform.HasValue)
				BuildAndRun (targetPlatform.Value, sceneList);
			else
				RunInEditor (sceneList);
		}
Exemple #8
0
		private static void BuildAndRun (BuildTarget target, List<string> sceneList)
		{
			var resultFilePath = GetParameterArgument (resultFileDirParam);

			int port = 0;
			List<string> ipList = TestRunnerConfigurator.GetAvailableNetworkIPs ();

			var config = new PlatformRunnerConfiguration ()
			{
				buildTarget = target,
				scenes = sceneList.ToArray (),
				projectName = "IntegrationTests",
				resultsDir = resultFilePath,
				sendResultsOverNetwork = InternalEditorUtility.inBatchMode,
				ipList = ipList,
				port = port
			};

			if (Application.isWebPlayer)
			{
				config.sendResultsOverNetwork = false;
				Debug.Log ("You can't use WebPlayer as active platform for running integraiton tests. Switching to Standalone");
				EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.StandaloneWindows);
			}

			PlatformRunner.BuildAndRunInPlayer (config);
		}
    private static void onPostProcessBuildPlayer( BuildTarget target, string pathToBuiltProject )
    {
        if( target == BuildTarget.iOS )
        {
            // grab the path to the postProcessor.py file
            var scriptPath = Path.Combine( Application.dataPath, "Editor/Vungle/VunglePostProcessor.py" );

            // sanity check
            if( !File.Exists( scriptPath ) )
            {
                UnityEngine.Debug.LogError( "Vungle post builder could not find the VunglePostProcessor.py file. Did you accidentally delete it?" );
                return;
            }

            var pathToNativeCodeFiles = Path.Combine( Application.dataPath, "Editor/Vungle/VungleSDK" );

            var args = string.Format( "\"{0}\" \"{1}\" \"{2}\"", scriptPath, pathToBuiltProject, pathToNativeCodeFiles );
            var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "python2.6",
                    Arguments = args,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true
                }
            };

            proc.Start();
        }
    }
    public static void BuildGame(BuildTarget buildTarget, BuildOptions buildOptions = BuildOptions.None)
    {
        if (BuildPipeline.isBuildingPlayer == false) {
            UnityEngine.Debug.ClearDeveloperConsole();

            var smcsFile = Path.Combine( Application.dataPath, "smcs.rsp" );
            var gmcsFile = Path.Combine( Application.dataPath, "gmcs.rsp" );

            // -define:debug;poop
            File.WriteAllText( smcsFile, "-define:BUILD" );
            File.WriteAllText( gmcsFile, "-define:BUILD" );

            AssetDatabase.Refresh();

            string[] scenes = GetSceneList();
            //string path = Application.dataPath.Remove(Application.dataPath.Length - 8, 7) + "_build";

            // Build player.
            BuildPipeline.BuildPlayer(scenes, path + "/" + StringManager.BUILDNAME + ".exe", buildTarget, buildOptions);

            // Copy a file from the project folder to the build folder, alongside the built game. eg:
            // FileUtil.CopyFileOrDirectory("Assets/WebPlayerTemplates/Readme.txt", path + "Readme.txt");

            //remove build thingies
            File.WriteAllText( smcsFile, "" );
            File.WriteAllText( gmcsFile, "" );
        }
    }
    private static void ProcessPostBuild(BuildTarget buildTarget, string path)
    {
        #if UNITY_IOS
        // We only need this IsSceneActive because we do not want to include the library data in other examples then the LibraryDemo
        if (buildTarget == BuildTarget.iOS && IsSceneActive("Assets/Scene/GoogleAdsUnity.unity")) {

            /*
            Debug.Log ("[UNITY_IOS] ProcessPostBuild - Xcode Manipulation API");

            string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";

            PBXProject proj = new PBXProject ();
            proj.ReadFromString (File.ReadAllText (projPath));

            string target = proj.TargetGuidByName ("Unity-iPhone");

            Debug.Log("Enabling modules: CLANG_ENABLE_MODULES = YES");
            proj.AddBuildProperty(target, "CLANG_ENABLE_MODULES", "YES");

            File.WriteAllText (projPath, proj.WriteToString ());
            */

        }
        #endif
    }
Exemple #12
0
	public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) {
#if !DISABLEREDISTCOPY
		string strProjectName = Path.GetFileNameWithoutExtension(pathToBuiltProject);

		if (target == BuildTarget.StandaloneWindows64) {
			CopyFile("steam_api64.dll", "steam_api64.dll", pathToBuiltProject);
		}
		else if (target == BuildTarget.StandaloneWindows) {
			CopyFile("steam_api.dll", "steam_api.dll", pathToBuiltProject);
		}
				
		string controllerCfg = Path.Combine(Application.dataPath, "controller.vdf");
		if (File.Exists(controllerCfg)) {
			string dir = "_Data";
			if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal) {
				dir = ".app/Contents";
			}

			string strFileDest = Path.Combine(Path.Combine(Path.GetDirectoryName(pathToBuiltProject), strProjectName + dir), "controller.vdf");

			File.Copy(controllerCfg, strFileDest);

			if (!File.Exists(strFileDest)) {
				Debug.LogWarning("[Steamworks.NET] Could not copy controller.vdf into the built project. File.Copy() Failed. Place controller.vdf from the Steamworks SDK in the output dir manually.");
			}
		}
#endif
	}
	public static void OnPostProcessBuild(BuildTarget target, string path)
	{

		if (target == BuildTarget.iOS)
		{
			// Get target for Xcode project
			string projPath = PBXProject.GetPBXProjectPath(path);
			PBXProject proj = new PBXProject();
			proj.ReadFromString(File.ReadAllText(projPath));

			string targetName = PBXProject.GetUnityTargetName();
			string projectTarget = proj.TargetGuidByName(targetName);

			// Add dependencies
			proj.AddFrameworkToProject(projectTarget, "AssetsLibrary.framework", false);
			proj.AddFrameworkToProject(projectTarget, "CoreText.framework", false);
			proj.AddFrameworkToProject(projectTarget, "MobileCoreServices.framework", false);
			proj.AddFrameworkToProject(projectTarget, "QuickLook.framework", false);
			proj.AddFrameworkToProject(projectTarget, "Security.framework", false);

			File.WriteAllText(projPath, proj.WriteToString());

			InsertAuthCodeIntoControllerClass(path);
			InsertUILoadedCallbackIntoControllerClass(path);
		}
	}
 public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
 {
     #if !UNITY_CLOUD_BUILD
     Debug.Log ("[UNITY_CLOUD_BUILD] OnPostprocessBuild");
     ProcessPostBuild (buildTarget, path);
     #endif
 }
    /// <summary>
    /// 生成绑定素材
    /// </summary>
    public static void BuildAssetResource(BuildTarget target)
    {
        if (Directory.Exists(Util.DataPath)) {
            Directory.Delete(Util.DataPath, true);
        }
        string streamPath = Application.streamingAssetsPath;
        if (Directory.Exists(streamPath)) {
            Directory.Delete(streamPath, true);
        }
        Directory.CreateDirectory(streamPath);
        AssetDatabase.Refresh();

        maps.Clear();
        if (AppConst.LuaBundleMode) {
            HandleLuaBundle();
        } else {
            HandleLuaFile();
        }
        if (AppConst.ExampleMode) {
            HandleExampleBundle();
        }
        string resPath = "Assets/" + AppConst.AssetDir;
        BuildAssetBundleOptions options = BuildAssetBundleOptions.DeterministicAssetBundle |
                                          BuildAssetBundleOptions.UncompressedAssetBundle;
        BuildPipeline.BuildAssetBundles(resPath, maps.ToArray(), options, target);
        BuildFileIndex();

        string streamDir = Application.dataPath + "/" + AppConst.LuaTempDir;
        if (Directory.Exists(streamDir)) Directory.Delete(streamDir, true);
        AssetDatabase.Refresh();
    }
        public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
        {
            if (target != BuildTarget.iPhone) {
                return;
            }

            #if NO_GPGS
            // remove plugin code from generated project
            string pluginDir = pathToBuiltProject + "/Libraries/Plugins/iOS";

            GPGSUtil.WriteFile(pluginDir + "/GPGSAppController.mm", "// Empty since NO_GPGS is defined\n");
            return;
            #endif

            if (GetBundleId() == null) {
                UnityEngine.Debug.LogError("The iOS bundle ID has not been set up through the " +
                "'iOS Setup' submenu of 'Google Play Games' - the generated xcode project will " +
                "not work properly.");
                return;
            }

            UnityEngine.Debug.Log("Adding URL Types for authentication using PlistBuddy.");

            UpdateGeneratedInfoPlistFile(pathToBuiltProject + "/Info.plist");
            UpdateGeneratedPbxproj(pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj");

            EditorWindow.GetWindow<GPGSInstructionWindow>(
                utility: true,
                title: "Building for IOS",
                focus: true);
        }
 public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs)
 {
   List<DefaultPackerPolicy.Entry> source1 = new List<DefaultPackerPolicy.Entry>();
   foreach (int importerInstanceId in textureImporterInstanceIDs)
   {
     TextureImporter textureImporter = EditorUtility.InstanceIDToObject(importerInstanceId) as TextureImporter;
     TextureFormat desiredFormat;
     ColorSpace colorSpace;
     int compressionQuality;
     textureImporter.ReadTextureImportInstructions(target, out desiredFormat, out colorSpace, out compressionQuality);
     TextureImporterSettings dest = new TextureImporterSettings();
     textureImporter.ReadTextureSettings(dest);
     foreach (Sprite sprite in ((IEnumerable<UnityEngine.Object>) AssetDatabase.LoadAllAssetRepresentationsAtPath(textureImporter.assetPath)).Select<UnityEngine.Object, Sprite>((Func<UnityEngine.Object, Sprite>) (x => x as Sprite)).Where<Sprite>((Func<Sprite, bool>) (x => (UnityEngine.Object) x != (UnityEngine.Object) null)).ToArray<Sprite>())
       source1.Add(new DefaultPackerPolicy.Entry()
       {
         sprite = sprite,
         settings = {
           format = desiredFormat,
           colorSpace = colorSpace,
           compressionQuality = !TextureUtil.IsCompressedTextureFormat(desiredFormat) ? 0 : compressionQuality,
           filterMode = !Enum.IsDefined(typeof (UnityEngine.FilterMode), (object) textureImporter.filterMode) ? UnityEngine.FilterMode.Bilinear : textureImporter.filterMode,
           maxWidth = 2048,
           maxHeight = 2048,
           generateMipMaps = textureImporter.mipmapEnabled,
           enableRotation = this.AllowRotationFlipping,
           allowsAlphaSplitting = textureImporter.GetAllowsAlphaSplitting(),
           paddingPower = !textureImporter.mipmapEnabled ? (uint) EditorSettings.spritePackerPaddingPower : 3U
         },
         atlasName = this.ParseAtlasName(textureImporter.spritePackingTag),
         packingMode = this.GetPackingMode(textureImporter.spritePackingTag, dest.spriteMeshType),
         anisoLevel = textureImporter.anisoLevel
       });
     Resources.UnloadAsset((UnityEngine.Object) textureImporter);
   }
   foreach (IGrouping<string, DefaultPackerPolicy.Entry> source2 in source1.GroupBy<DefaultPackerPolicy.Entry, string, DefaultPackerPolicy.Entry>((Func<DefaultPackerPolicy.Entry, string>) (e => e.atlasName), (Func<DefaultPackerPolicy.Entry, DefaultPackerPolicy.Entry>) (e => e)))
   {
     int num = 0;
     IEnumerable<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>> source3 = source2.GroupBy<DefaultPackerPolicy.Entry, AtlasSettings, DefaultPackerPolicy.Entry>((Func<DefaultPackerPolicy.Entry, AtlasSettings>) (t => t.settings), (Func<DefaultPackerPolicy.Entry, DefaultPackerPolicy.Entry>) (t => t));
     foreach (IGrouping<AtlasSettings, DefaultPackerPolicy.Entry> grouping in source3)
     {
       string key1 = source2.Key;
       if (source3.Count<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>>() > 1)
         key1 += string.Format(" (Group {0})", (object) num);
       AtlasSettings key2 = grouping.Key;
       key2.anisoLevel = 1;
       if (key2.generateMipMaps)
       {
         foreach (DefaultPackerPolicy.Entry entry in (IEnumerable<DefaultPackerPolicy.Entry>) grouping)
         {
           if (entry.anisoLevel > key2.anisoLevel)
             key2.anisoLevel = entry.anisoLevel;
         }
       }
       job.AddAtlas(key1, key2);
       foreach (DefaultPackerPolicy.Entry entry in (IEnumerable<DefaultPackerPolicy.Entry>) grouping)
         job.AssignToAtlas(key1, entry.sprite, entry.packingMode, SpritePackingRotation.None);
       ++num;
     }
   }
 }
 public static void RunIntegrationTests(BuildTarget? targetPlatform, List<string> testScenes, List<string> otherBuildScenes)
 {
     if (targetPlatform.HasValue)
         BuildAndRun(targetPlatform.Value, testScenes, otherBuildScenes);
     else
         RunInEditor(testScenes,  otherBuildScenes);
 }
    public static void OnPostProcessBuild(BuildTarget target, string path)
    {
        Debug.Log("New Post Processing Build: OnPostProcessBuild: path = " + path);

        // 1: Proceed only if this is an iOS build

        #if UNITY_IPHONE

        string xcodeprojPath = Path.Combine(path, DEFAULT_UNITY_IPHONE_PROJECT_NAME);

          	Debug.Log("We found xcodeprojPath to be : " + xcodeprojPath);

        // 2: We init our tab and process our project
        // NOTE: !! MobileAppTracker.framework !! must be the first item in this array.
        framework[] myFrameworks = { new framework(FRAMEWORK_MOBILEAPPTRACKER, FRAMEWORK_ID_MOBILEAPPTRACKER, FRAMEWORK_FILEREFID_MOBILEAPPTRACKER, Path.GetDirectoryName(xcodeprojPath), false),
                                     new framework(FRAMEWORK_ADSUPPORT, FRAMEWORK_ID_ADSUPPORT, FRAMEWORK_FILEREFID_ADSUPPORT, null, true),
                                     new framework(FRAMEWORK_CORETELEPHONY, FRAMEWORK_ID_CORETELEPHONY, FRAMEWORK_FILEREFID_CORETELEPHONY, null, true),
                                     new framework(FRAMEWORK_MOBILECORESERVICES, FRAMEWORK_ID_MOBILECORESERVICES, FRAMEWORK_FILEREFID_MOBILECORESERVICES, null, true),
                                     new framework(FRAMEWORK_SYSTEMCONFIGURATION, FRAMEWORK_ID_SYSTEMCONFIGURATION, FRAMEWORK_FILEREFID_SYSTEMCONFIGURATION, null, true),
        };

        Debug.Log("OnPostProcessBuild - START");

        updateXcodeProject(xcodeprojPath, myFrameworks);

        #else
        // 3: We do nothing if not iPhone
        Debug.Log("OnPostProcessBuild - Warning: No PostProcessing required. This is not an iOS build");
        #endif
        Debug.Log("OnPostProcessBuild - END");
    }
Exemple #20
0
    void OnGUI()
    {
        _buildTarget = (BuildTarget)EditorGUILayout.EnumPopup("BuildTarget: ", _buildTarget);

        EditorGUILayout.BeginHorizontal();
        if(GUILayout.Button("打包DLL资源", GUILayout.Width(100), GUILayout.Height(50)))
        {
            _CreateAssetBundle(_assetsRoot + _bundleResRoot + _bundleDll + "/", _assetsRoot + _bundleRoot + _bundleDll + _bundleExt);
            AssetDatabase.Refresh();
        }

        if (GUILayout.Button("打包GUI资源", GUILayout.Width(100), GUILayout.Height(50)))
        {
            _CreateAssetBundle(_assetsRoot + _bundleResRoot + _bundleGUI + "/", _assetsRoot + _bundleRoot + _bundleGUI + _bundleExt);
            AssetDatabase.Refresh();
        }

        if (GUILayout.Button("打包CONFIG资源", GUILayout.Width(100), GUILayout.Height(50)))
        {
            _CreateAssetBundle(_assetsRoot + _bundleResRoot + _bundleCFG + "/", _assetsRoot + _bundleRoot + _bundleCFG + _bundleExt);
            AssetDatabase.Refresh();
        }

        if (GUILayout.Button("打包所有资源", GUILayout.Width(100), GUILayout.Height(50)))
        {
            _CreateAssetBundle(_assetsRoot + _bundleResRoot + _bundleDll + "/", _assetsRoot + _bundleRoot + _bundleDll + _bundleExt);
            _CreateAssetBundle(_assetsRoot + _bundleResRoot + _bundleGUI + "/", _assetsRoot + _bundleRoot + _bundleGUI + _bundleExt);
            _CreateAssetBundle(_assetsRoot + _bundleResRoot + _bundleCFG + "/", _assetsRoot + _bundleRoot + _bundleCFG + _bundleExt);
            AssetDatabase.Refresh();
        }
        EditorGUILayout.EndHorizontal();
    }
        public static void OnPostProcessBuild( BuildTarget target, string pathToBuiltProject )
        {
            #if UNITY_5 || UNITY_6 || UNITY_7
            if (target != BuildTarget.iOS)
            #else
            if (target != BuildTarget.iPhone)
            #endif
            {
                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 void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs)
    {
        List<Entry> entries = new List<Entry>();

        foreach (int instanceID in textureImporterInstanceIDs)
        {
            TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter;

            //TextureImportInstructions ins = new TextureImportInstructions();
            //ti.ReadTextureImportInstructions(ins, target);

            TextureImporterSettings tis = new TextureImporterSettings();
            ti.ReadTextureSettings(tis);

            Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray();
            foreach (Sprite sprite in sprites)
            {
                //在这里设置每个图集的参数
                Entry entry = new Entry();
                entry.sprite = sprite;
                entry.settings.format = (TextureFormat)Enum.Parse(typeof(TextureFormat), ParseTextuerFormat(ti.spritePackingTag).ToString());
                entry.settings.filterMode = FilterMode.Bilinear;
                entry.settings.colorSpace = ColorSpace.Linear;
                entry.settings.compressionQuality = (int)TextureCompressionQuality.Normal;
                entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear;
                entry.settings.maxWidth = ParseTextureWidth(ti.spritePackingTag);
                entry.settings.maxHeight = ParseTextureHeight(ti.spritePackingTag);
                entry.atlasName = ParseAtlasName(ti.spritePackingTag);
                entry.packingMode = GetPackingMode(ti.spritePackingTag, tis.spriteMeshType);

                entries.Add(entry);
            }
            Resources.UnloadAsset(ti);
        }

        var atlasGroups =
            from e in entries
            group e by e.atlasName;
        foreach (var atlasGroup in atlasGroups)
        {
            int page = 0;
            // Then split those groups into smaller groups based on texture settings
            var settingsGroups =
                from t in atlasGroup
                group t by t.settings;
            foreach (var settingsGroup in settingsGroups)
            {
                string atlasName = atlasGroup.Key;
                if (settingsGroups.Count() > 1)
                    atlasName += string.Format(" (Group {0})", page);

                job.AddAtlas(atlasName, settingsGroup.Key);
                foreach (Entry entry in settingsGroup)
                {
                    job.AssignToAtlas(atlasName, entry.sprite, entry.packingMode, SpritePackingRotation.None);
                }
                ++page;
            }
        }
    }
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        string baseFolder = pathToBuiltProject.Substring(0, pathToBuiltProject.Length - 4) + "_Data/";

        Debug.Log( "BuiltProject path " + baseFolder );

        Debug.Log ("Copying files...");

        Directory.CreateDirectory(baseFolder + "Composition/FiniteStateMachines");
        string[] fsms = Directory.GetFiles(Application.dataPath + "/Composition/FiniteStateMachines", "*.tgf");
        foreach (string tgfFile in fsms)
        {
            string fileName = Path.GetFileName(tgfFile);
            File.Copy (tgfFile, baseFolder + "Composition/FiniteStateMachines/" + fileName);
        }

        Directory.CreateDirectory(baseFolder + "Composition/PathfindingGraphs");
        string[] graphs = Directory.GetFiles(Application.dataPath + "/Composition/PathfindingGraphs", "*.tgf");
        foreach (string tgfFile in graphs)
        {
            string fileName = Path.GetFileName(tgfFile);
            File.Copy (tgfFile, baseFolder + "Composition/PathfindingGraphs/" + fileName);
        }

        Debug.Log ("Copying files... DONE!");
    }
 public static void OnPostExportBuild(BuildTarget buildTarget, string path)
 {
     #if !UNITY_CLOUD_BUILD
     Debug.Log("[Editor] OnPostExportBuild started.");
     ProcessPostBuild(buildTarget, path);
     #endif
 }
		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 pathToBuildProject)
    {
        if (target == BuildTarget.tvOS) {
            UnityEngine.Debug.Log ("[SPIL] Starting custom post process build script." + pathToBuildProject);

            UnityEngine.Debug.Log ("[SPIL] Moving SpilTV.framework to the root of the project");
            MoveDirectory (pathToBuildProject + "/Frameworks/Plugins/tvOS/SpilTV.framework", pathToBuildProject + "/SpilTV.framework");

            bool exportDefaultEntitlements = EditorPrefs.GetBool ("exportDefaultEntitlements");
            bool useICloudContainer = EditorPrefs.GetBool ("useICloudContainer");
            bool useICloudKV = EditorPrefs.GetBool ("useICloudKV");
            bool usePushNotifications = EditorPrefs.GetBool ("usePushNotifications");

            String arguments = "Unity-iPhone " +
                                   exportDefaultEntitlements + " " +
                                   useICloudContainer + " " +
                                   useICloudKV + " " +
                                   usePushNotifications;

            UnityEngine.Debug.Log ("[SPIL] Executing: python " + pathToBuildProject + "/SpilTV.framework/setup.py " + arguments);
            Process setupProcess = new Process ();
            setupProcess.StartInfo.WorkingDirectory = pathToBuildProject;
            setupProcess.StartInfo.FileName = "python";
            setupProcess.StartInfo.Arguments = "SpilTV.framework/setup.py " + arguments;
            setupProcess.StartInfo.UseShellExecute = false;
            setupProcess.StartInfo.RedirectStandardOutput = true;
            setupProcess.Start ();
            setupProcess.WaitForExit ();

            UnityEngine.Debug.Log ("[SPIL] --> Setup.py output: " + setupProcess.StandardOutput.ReadToEnd ());

            UnityEngine.Debug.Log ("[SPIL] Custom post process build script finished executing!");
        }
    }
Exemple #27
0
 private static string GetPlatformForAssetBundles(BuildTarget target)
 {
     switch(target)
     {
     case BuildTarget.Android:
         return "Android";
     case BuildTarget.iOS:
         return "iOS";
     case BuildTarget.WebGL:
         return "WebGL";
     case BuildTarget.WebPlayer:
         return "WebPlayer";
     case BuildTarget.StandaloneWindows:
     case BuildTarget.StandaloneWindows64:
         return "Windows";
     case BuildTarget.StandaloneOSXIntel:
     case BuildTarget.StandaloneOSXIntel64:
     case BuildTarget.StandaloneOSXUniversal:
         return "OSX";
         // Add more build targets for your own.
         // If you add more targets, don't forget to add the same platforms to GetPlatformForAssetBundles(RuntimePlatform) function.
     default:
         return null;
     }
 }
    static void CreateBaseCharacter(BuildTarget target)
    {
        foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets))
        {
            // If the object is not GameObject, then skip this object
            if ((obj is GameObject) == false)
            {
                continue;
            }

            // If the object is of animation prefab type, then skip this object
            if (obj.name.Contains("@"))
            {
                continue;
            }

            if (obj is Texture2D) continue;

            string name = obj.name.ToLower();

            GameObject go = (GameObject)obj;

            GenerateBaseCharacter(go, name, target);
        }
    }
		public PlatformArchitecture(string name, string binarySuffix, BuildTarget buildTarget, bool isActive = false)
		{
			this.name = name;
			this.binarySuffix = binarySuffix;
			this.buildTarget = buildTarget;
			this.isActive = isActive;
		}
    public static void OnPostprocessBuild(BuildTarget target,
      string pathToBuildProject)
    {
        if (target != BuildTarget.iOS)
        {
          return;
        }

        string script = "CountlyXCodePostprocessor.py";
        string pathToXCodeProject = GetXCodeProjectPath(pathToBuildProject);
        string args = String.Format("\"{0}\"", pathToXCodeProject);
        string result;
        int exitCode;

        try
        {
          exitCode = ExecuteScript(script, args, out result);
        }
        catch (Exception e)
        {
          Debug.LogError("CountlyPostprocessor: Could not execute " +
          script + "! Make sure the script has executable permissions!\n" +
          "Exception: (" + e + ")");
          return;
        }

        if ((exitCode != 0) || (string.IsNullOrEmpty(result)))
        {
          Debug.LogError("CountlyPostprocessor: Postprocess failed: " + result);
          return;
        }

        Debug.Log(result);
    }
 public extern static CanAppendBuild BuildCanBeAppended(BuildTarget target, string location);
 public static bool IsMobilePlatform(BuildTarget target)
 {
     return(BuildTargetDiscovery.PlatformHasFlag(target, TargetAttributes.HasIntegratedGPU));
 }
Exemple #33
0
 public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget)
 {
     CheckEnableControlRig();
 }
 extern internal static string[] GetCompilationDefines(EditorScriptCompilationOptions options, BuildTargetGroup targetGroup, BuildTarget target, ApiCompatibilityLevel apiCompatibilityLevel);
 extern internal static PrecompiledAssembly[] GetPrecompiledAssemblies(bool buildingForEditor, BuildTargetGroup buildTargetGroup, BuildTarget target);
 extern private static PrecompiledAssembly[] GetUnityAssembliesInternal(bool buildingForEditor, BuildTarget target);
 internal static PrecompiledAssembly[] GetUnityAssemblies(bool buildingForEditor, BuildTargetGroup buildTargetGroup, BuildTarget target)
 {
     return(GetUnityAssembliesInternal(buildingForEditor, target));
 }
 extern internal static bool IsUnityExtensionCompatibleWithEditor(BuildTargetGroup targetGroup, BuildTarget target, string path);
        static private void AddReferencedAssembliesRecurse(string assemblyPath, List <string> alreadyFoundAssemblies, string[] allAssemblyPaths, string[] foldersToSearch, Dictionary <string, AssemblyDefinition> cache, BuildTarget target)
        {
            if (IgnoreAssembly(assemblyPath, target))
            {
                return;
            }

            if (!File.Exists(assemblyPath))
            {
                return;
            }

            AssemblyDefinition assembly = GetAssemblyDefinitionCached(assemblyPath, cache);

            if (assembly == null)
            {
                throw new System.ArgumentException("Referenced Assembly " + Path.GetFileName(assemblyPath) + " could not be found!");
            }

            // Ignore it if we already added the assembly
            if (alreadyFoundAssemblies.IndexOf(assemblyPath) != -1)
            {
                return;
            }

            alreadyFoundAssemblies.Add(assemblyPath);

            var architectureSpecificPlugins = PluginImporter.GetImporters(target).Where(i =>
            {
                var cpu = i.GetPlatformData(target, "CPU");
                return(!string.IsNullOrEmpty(cpu) && !string.Equals(cpu, "AnyCPU", StringComparison.InvariantCultureIgnoreCase));
            }).Select(i => Path.GetFileName(i.assetPath)).Distinct();

            // Go through all referenced assemblies
            foreach (AssemblyNameReference referencedAssembly in assembly.MainModule.AssemblyReferences)
            {
                // Special cases for Metro
                if (referencedAssembly.Name == "BridgeInterface")
                {
                    continue;
                }
                if (referencedAssembly.Name == "WinRTBridge")
                {
                    continue;
                }
                if (referencedAssembly.Name == "UnityEngineProxy")
                {
                    continue;
                }
                if (IgnoreAssembly(referencedAssembly.Name + ".dll", target))
                {
                    continue;
                }

                string foundPath = FindAssemblyName(referencedAssembly.FullName, referencedAssembly.Name, allAssemblyPaths, foldersToSearch, cache);

                if (foundPath == "")
                {
                    // Ignore architecture specific plugin references
                    var found = false;
                    foreach (var extension in new[] { ".dll", ".winmd" })
                    {
                        if (architectureSpecificPlugins.Any(p => string.Equals(p, referencedAssembly.Name + extension, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                    {
                        continue;
                    }
                    throw new System.ArgumentException(string.Format("The Assembly {0} is referenced by {1} ('{2}'). But the dll is not allowed to be included or could not be found.",
                                                                     referencedAssembly.Name,
                                                                     assembly.MainModule.Assembly.Name.Name,
                                                                     assemblyPath));
                }

                AddReferencedAssembliesRecurse(foundPath, alreadyFoundAssemblies, allAssemblyPaths, foldersToSearch, cache, target);
            }
        }
 extern public static bool HasAdvancedLicenseOnBuildTarget(BuildTarget target);
Exemple #41
0
 static void GenericBuild(string[] scenes, string target_dir, BuildTarget build_target, BuildOptions build_options)
 {
     EditorUserBuildSettings.SwitchActiveBuildTarget(build_target);
 }
 //CLIENT
 /// <summary>Builds a client for the target platform.</summary>
 public static void BuildClient(BuildTarget targetPlatform)
 {
     Build(targetPlatform, NetworkType.Client);
 }
 //HEADLESS SERVER
 /// <summary>Builds a headless server for the target platform.</summary>
 public static void BuildHeadlessServer(BuildTarget targetPlatform)
 {
     Build(targetPlatform, NetworkType.Server, true);
 }
        //BUILD
        /// <summary>Builds an application using the passed in parameters.</summary>
        /// <param name="targetPlatform">BuildTarget.StandaloneWindows64, StandaloneLinux64, StandaloneOSX</param>
        /// <param name="buildType">NetworkType.Server - Client - HostAndPlay</param>
        /// <param name="headless">Build in headless mode? (console application)</param>
        public static void Build(BuildTarget targetPlatform, NetworkType buildType, bool headless = false)
        {
            ChangeBuildMenu.SetBuildType(buildType, headless); //ACTIVATE CHANGE BUILD MENU

            FileExtension buildFileExtension = FileExtension.exe;

            switch (targetPlatform)
            {
            //STANDALONE
            case BuildTarget.StandaloneWindows64: buildFileExtension = FileExtension.exe; break;

            case BuildTarget.StandaloneWindows: buildFileExtension = FileExtension.exe; break;

            case BuildTarget.StandaloneLinux64: buildFileExtension = FileExtension.x86_64; break;

            case BuildTarget.StandaloneOSX: buildFileExtension = FileExtension.app; break;

                /*TODO
                 *  //MOBILE
                 * case BuildTarget.iOS: break;
                 * case BuildTarget.Android: break;
                 *  //CONSOLE
                 * case BuildTarget.PS4: break;
                 * case BuildTarget.XboxOne: break;
                 * case BuildTarget.Switch: break;
                 *  //WEB
                 * case BuildTarget.WebGL: break;
                 *  //OTHER
                 * case BuildTarget.WSAPlayer: break;
                 * case BuildTarget.tvOS: break;
                 * case BuildTarget.Lumin: break;
                 * case BuildTarget.Stadia: break;
                 * case BuildTarget.NoTarget: break;
                 */
            }

            //SETUP BUILD OPTIONS
            BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();

            buildPlayerOptions.scenes           = GetScenesFromBuild();
            buildPlayerOptions.locationPathName = "_BUILD" + "/" + buildType.ToString().ToUpper() + "/" + targetPlatform + "/" + buildType.ToString().ToLower() + "." + buildFileExtension;
            buildPlayerOptions.target           = targetPlatform;
            buildPlayerOptions.options          = (headless) ? (BuildOptions.EnableHeadlessMode) : (BuildOptions.None);

            #region  BUILD REPORT - header
#if !SKIP_BUILD_REPORT
            buildLog.AppendLine("<b>[BUILD] " + targetPlatform + " - " + ((headless) ? "(headless) " : "") + buildType + "</b>"
                                + "\n" + buildPlayerOptions.locationPathName);

            foreach (string scenePath in buildPlayerOptions.scenes)
            {
                buildLog.AppendLine(scenePath);
            }
#endif
            #endregion

            //BUILD REPORTING
            BuildReport  report  = BuildPipeline.BuildPlayer(buildPlayerOptions);
            BuildSummary summary = report.summary;

            //SUCCESS
            if (summary.result == BuildResult.Succeeded)
            {
                #region  BUILD REPORT - success
#if !SKIP_BUILD_REPORT
                float sizeInMegabytes = (summary.totalSize / 1024f / 1024f);
                sizeInMegabytes -= sizeInMegabytes % 0.0001f;
                float durationInSeconds = (float)((summary.buildEndedAt - summary.buildStartedAt).TotalSeconds);
                durationInSeconds -= durationInSeconds % 0.01f;

                buildLog.AppendLine("<color=green><b>" + targetPlatform + " " + buildType + " build succeeded..." + "</b></color>"
                                    + ((summary.totalSize > 0) ? ("\nBuild size: " + sizeInMegabytes + " MB") : (""))
                                    + "\nBuild duration: " + durationInSeconds + "s");
#endif
                #endregion
            }
            //FAILURE
            if (summary.result == BuildResult.Failed)
            {
                #region  BUILD REPORT - failure
#if !SKIP_BUILD_REPORT
                buildLog.AppendLine("<color=red><b>" + targetPlatform + " " + buildType + " build failed...</b></color>"
                                    + "\n" + report.ToString());
#endif
                #endregion
            }
        }
Exemple #45
0
    private static AssetBundleManifest BuildAssetBundle(string path, BuildTarget target, List <GameConfig> games)
    {
        var builds = new List <AssetBundleBuild>();
        var abs    = AssetDatabase.GetAllAssetBundleNames();

        foreach (var ab in abs)
        {
            //1,筛选平台
            if (ab.EndsWith(".pc"))
            {
                if (target != BuildTarget.StandaloneWindows &&
                    target != BuildTarget.StandaloneWindows64 &&
                    target != BuildTarget.StandaloneOSXIntel &&
                    target != BuildTarget.StandaloneOSXIntel64 &&
                    target != BuildTarget.StandaloneOSXUniversal)
                {
                    continue;
                }
            }
            else if (ab.EndsWith(".mp"))
            {
                if (target != BuildTarget.iOS &&
                    target != BuildTarget.Android)
                {
                    continue;
                }
            }

            //2,筛选游戏
            if (ab.Contains("games/"))
            {
                string name = new FileInfo(ab).Directory.Name;
                if (games == null)
                {
                    continue;
                }

                var gameConfig = games.Find(config => name.Contains(config.ID.ToString()));
                if (gameConfig == null)
                {
                    continue;
                }

                if (!gameConfig.Packed)
                {
                    continue;
                }
            }

            //string dir = new FileInfo(ab).Directory.Name;
            var build = new AssetBundleBuild();
            build.assetBundleName    = Path.GetDirectoryName(ab) + "/" + Path.GetFileNameWithoutExtension(ab);
            build.assetNames         = AssetDatabase.GetAssetPathsFromAssetBundle(ab);
            build.assetBundleVariant = Path.GetExtension(ab).Replace(".", "");
            builds.Add(build);

            Debug.Log("name:" + build.assetBundleName + " variant:" + build.assetBundleVariant + " ab:" + ab);
        }

        Debug.Log("Build scene for target:" + target + " by path:" + path);

        if (EditorUserBuildSettings.activeBuildTarget != target)
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(target);
        }

        return(BuildPipeline.BuildAssetBundles(
                   path,
                   builds.ToArray(),
                   BuildAssetBundleOptions.DeterministicAssetBundle /* |
                                                                     * BuildAssetBundleOptions.ForceRebuildAssetBundle*/,
                   target
                   ));
    }
 //SERVER
 /// <summary>Builds a server for the target platform. It is recommended to use a Headless Server instead.</summary>
 public static void BuildServer(BuildTarget targetPlatform)
 {
     Build(targetPlatform, NetworkType.Server);
 }
Exemple #47
0
        public static void OnPostprocessBuild(BuildTarget target, string projectPath)
        {
            var pbxProjPath = PBXProject.GetPBXProjectPath(projectPath);
            var proj        = new PBXProject();

            proj.ReadFromFile(pbxProjPath);

            #if UNITY_2019_3_OR_NEWER
            var targetGuid          = proj.GetUnityMainTargetGuid();
            var frameworkTargetGuid = proj.GetUnityFrameworkTargetGuid();
            #else
            var targetGuid          = proj.TargetGuidByName("Unity-iPhone");
            var frameworkTargetGuid = proj.TargetGuidByName("Unity-iPhone");
            #endif

            RegisterAppLanguages();

            AddFlags(proj, targetGuid);
            AddLibraries(proj, targetGuid);
            AddFrameworks(proj, frameworkTargetGuid, target);
            AddEmbeddedFrameworks(proj, targetGuid);
            AddPlistVariables(projectPath);
            ApplyBuildSettings(proj, frameworkTargetGuid);
            CopyAssetFiles(proj, projectPath, targetGuid);
            AddShellScriptBuildPhase(proj, targetGuid);

            proj.WriteToFile(pbxProjPath);

            var capManager = new ProjectCapabilityManager(pbxProjPath, ISD_Settings.ENTITLEMENTS_FILE_NAME, "Unity-iPhone");
            AddCapabilities(capManager);
            capManager.WriteToFile();

            //Some API simply does not work so on this block we are applying a workaround
            //after Unity deploy scrips has stopped working

            //Adding Embedded Frameworks
            foreach (var framework in ISD_Settings.Instance.EmbededFrameworks)
            {
                var contents    = File.ReadAllText(pbxProjPath);
                var pattern     = "(?<=Embed Frameworks)(?:.*)(\\/\\* " + framework.FileName + "\\ \\*\\/)(?=; };)";
                var oldText     = "/* " + framework.FileName + " */";
                var updatedText = "/* " + framework.FileName + " */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }";
                contents = Regex.Replace(contents, pattern, m => m.Value.Replace(oldText, updatedText));
                File.WriteAllText(pbxProjPath, contents);
            }


            var entitlementsPath = projectPath + "/" + ISD_Settings.ENTITLEMENTS_FILE_NAME;
            if (ISD_Settings.Instance.EntitlementsMode == ISD_EntitlementsGenerationMode.Automatic)
            {
                if (ISD_Settings.Instance.Capability.iCloud.Enabled)
                {
                    if (ISD_Settings.Instance.Capability.iCloud.keyValueStorage && !ISD_Settings.Instance.Capability.iCloud.iCloudDocument)
                    {
                        var entitlements = new PlistDocument();
                        entitlements.ReadFromFile(entitlementsPath);

                        var plistVariable = new PlistElementArray();
                        entitlements.root["com.apple.developer.icloud-container-identifiers"] = plistVariable;

                        entitlements.WriteToFile(entitlementsPath);
                    }
                }
            }
            else
            {
                if (ISD_Settings.Instance.EntitlementsFile != null)
                {
                    var    entitlementsContentPath = SA_AssetDatabase.GetAbsoluteAssetPath(ISD_Settings.Instance.EntitlementsFile);
                    string contents = File.ReadAllText(entitlementsContentPath);
                    File.WriteAllText(entitlementsPath, contents);
                }
                else
                {
                    Debug.LogWarning("ISD: EntitlementsMode set to Manual but no file provided");
                }
            }
        }
 //HEADLESS SERVER + CLIENT
 /// <summary>Builds a client and a headless server back to back.</summary>
 public static void BuildClientAndHeadlessServer(BuildTarget targetPlatform)
 {
     BuildHeadlessServer(targetPlatform);
     BuildClient(targetPlatform);
 }
 public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
 {
     CopyPluginsForStandaloneBuildIfRequired(buildTarget);
 }
Exemple #50
0
    public static bool BuildAssetBundle(string path, BuildTarget target, List <GameConfig> games, ref List <AssetBundleInfo> abList)
    {
        try
        {
            string gamesDir = path + "games/";
            if (!Directory.Exists(gamesDir))
            {
                Directory.CreateDirectory(gamesDir);
            }

            if (EditorUserBuildSettings.activeBuildTarget != target)
            {
                EditorUserBuildSettings.SwitchActiveBuildTarget(target);
            }

            foreach (var game in games)
            {
                if (!game.Packed)
                {
                    continue;
                }

                var abPath = Array.Find(game.AssetBundles, s => s.Contains(GlobalConst.Res.SceneFileExt));
                if (string.IsNullOrEmpty(abPath))
                {
                    continue;
                }

                string name            = Path.GetFileNameWithoutExtension(abPath);
                string destDirFileName = path + abPath;
                string destDirPath     = Path.GetDirectoryName(destDirFileName);
                if (!Directory.Exists(destDirPath))
                {
                    Directory.CreateDirectory(destDirPath);
                }

                /*if (abList.Exists(item => string.Compare(item.Name, name, true) == 0))
                 * {
                 *  Debug.Log("the scene was already build. FileName:" + name);
                 *  continue;
                 * }*/

                Debug.Log("build scene from :" + game.SceneName + " dest:" + abPath);

                string res = BuildPipeline.BuildPlayer(
                    new string[] { game.SceneName },
                    destDirFileName,
                    target,
                    BuildOptions.BuildAdditionalStreamedScenes);

                if (res.Length > 0)
                {
                    Debug.LogError(res);
                    return(false);
                }

                name = abPath.Replace(Path.GetExtension(abPath), "");

                var data_type = new AssetBundleInfo();
                //data_type.ID = "";
                data_type.Name     = name;
                data_type.FileName = abPath;
                data_type.Hash     = MD5Util.GetFileMD5(destDirFileName);
                data_type.Version  = GameVersion.GetProductVersion(game.Version).ToString();

                var oldItem = abList.Find(item => { return(string.Compare(item.Name, name, true) == 0); });
                if (oldItem != null)
                {
                    abList.Remove(oldItem);
                }

                Debug.Log("add builded scene:" + data_type + " name:" + name);
                abList.Add(data_type);
            }

            var manifest = BuildAssetBundle(path, target, games);
            if (manifest == null)
            {
                Debug.Log("null manifest");
                return(true);
            }

            string[] assetBundles = manifest.GetAllAssetBundles();
            foreach (var ab in assetBundles)
            {
                string name = ab.Replace(Path.GetExtension(ab), "");

                var data_type = new AssetBundleInfo();
                //data_type.ID = "";
                data_type.Name     = name;
                data_type.FileName = ab;
                data_type.Hash     = MD5Util.GetFileMD5(path + ab);
                data_type.Version  = "0";

                var oldItem = abList.Find(item => { return(string.Compare(item.Name, name, true) == 0); });
                if (oldItem != null)
                {
                    abList.Remove(oldItem);

                    if (string.Compare(oldItem.Hash, data_type.Hash, true) != 0)
                    {
                        data_type.UpdateVersion();
                    }
                }

                Debug.Log("add builded ab:" + data_type + " name:" + name);
                abList.Add(data_type);
            }

            Debug.Log("assetbundle build finish");
            return(true);
        }
        catch (Exception e)
        {
            Debug.LogException(e);
            return(false);
        }
    }
        public void Configure(AssetImporter referenceImporter, AssetImporter importer, BuildTarget target, string group)
        {
            var r = referenceImporter as ModelImporter;
            var t = importer as ModelImporter;

            if (r == null || t == null)
            {
                throw new AssetGraphException(string.Format("Invalid AssetImporter assigned for {0}", importer.assetPath));
            }
            OverwriteImportSettings(t, r);
        }
Exemple #52
0
        static BuildTargetGroup GetGroupFromBuildTarget(BuildTarget buildTarget)
        {
            switch (buildTarget)
            {
            case BuildTarget.StandaloneOSX:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneOSXIntel64:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneOSXIntel:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneWindows64:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneWindows:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneLinux64:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneLinux:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.StandaloneLinuxUniversal:
                return(BuildTargetGroup.Standalone);

            case BuildTarget.Android:
                return(BuildTargetGroup.Android);

            case BuildTarget.iOS:
                return(BuildTargetGroup.iOS);

            case BuildTarget.WebGL:
                return(BuildTargetGroup.WebGL);

            case BuildTarget.WSAPlayer:
                return(BuildTargetGroup.WSA);

            case BuildTarget.Tizen:
                return(BuildTargetGroup.Tizen);

            case BuildTarget.PSP2:
                return(BuildTargetGroup.PSP2);

            case BuildTarget.PS4:
                return(BuildTargetGroup.PS4);

            case BuildTarget.PSM:
                return(BuildTargetGroup.PSM);

            case BuildTarget.XboxOne:
                return(BuildTargetGroup.XboxOne);

            case BuildTarget.SamsungTV:
                return(BuildTargetGroup.SamsungTV);

            case BuildTarget.N3DS:
                return(BuildTargetGroup.N3DS);

            case BuildTarget.WiiU:
                return(BuildTargetGroup.WiiU);

            case BuildTarget.tvOS:
                return(BuildTargetGroup.tvOS);

            case BuildTarget.NoTarget:
                return(BuildTargetGroup.Unknown);

            default:
                return(BuildTargetGroup.Unknown);
            }
        }
Exemple #53
0
    //
    /// <summary>
    /// 生成AssetBundle
    /// </summary>
    /// <param name="resRootPath"></param>
    /// <param name="outPath"></param>
    /// <param name="target"></param>
    public static void GenAssetBundle(string resRootPath, string outPath, BuildTarget target,
                                      BuildAssetBundleOptions options = BuildAssetBundleOptions.ChunkBasedCompression)
    {
        //1.生成ab名
        string rootPath = IPath.Combine(Application.dataPath, resRootPath);

        //扫描所有文件
        var allFiles = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
        var fileList = new List <string>(allFiles);

        //剔除不打包的部分
        for (int i = fileList.Count - 1; i >= 0; i--)
        {
            var fi        = allFiles[i];
            var extension = Path.GetExtension(fi.ToLower());
            //
            if (extension.ToLower() == ".meta" || extension.ToLower() == ".cs" || extension.ToLower() == ".js")
            {
                fileList.RemoveAt(i);
            }
        }

        AnalyzeResource(fileList.ToArray(), target, outPath);

        //配置写入本地
        var configPath = IPath.Combine(outPath, "Art/Config.json");

        //2.打包
        //更新的部分放在另外一个路径
        //然后再合并
        var newpath = outPath;

        if (File.Exists(configPath))
        {
            newpath = outPath + "/Art_new";
            if (Directory.Exists(newpath))
            {
                Directory.Delete(newpath);
            }

            Directory.CreateDirectory(newpath);
        }

        //3.生成AssetBundle
        BuildAssetBundle(target, newpath, options);

        //保存last.json
        if (File.Exists(configPath))
        {
            var lastPath = IPath.Combine(outPath, "Art/Config_last.json");
            File.Copy(configPath, lastPath, true);
        }

        var direct = Path.GetDirectoryName(configPath);

        if (Directory.Exists(direct) == false)
        {
            Directory.CreateDirectory(direct);
        }

        File.WriteAllText(configPath, curManifestConfig.ToString());

        //合并
//        if (newpath != outPath)
//        {
//            var newFs = Directory.GetFiles(newpath, "*.*", SearchOption.AllDirectories);
//
//            foreach (var nf in newFs)
//            {
//                var filename = nf.Replace(newpath, "");
//                var copyto = IPath.Combine(outPath, filename);
//                File.Copy(nf,copyto,true);
//                Debug.Log("合并新文件:" + nf);
//            }
//        }

        //  Directory.Delete(newpath,true);


        //4.清除AB Name
        RemoveAllAbName();

        //删除无用文件
        var delFiles = Directory.GetFiles(outPath, "*.*", SearchOption.AllDirectories);

        foreach (var df in delFiles)
        {
            var ext = Path.GetExtension(df);
            if (ext == ".meta" || ext == ".manifest")
            {
                File.Delete(df);
            }
        }
    }
Exemple #54
0
    public static void BuildiPhoneResource()
    {
        BuildTarget target = BuildTarget.iOS;

        BuildAssetResource(target);
    }
Exemple #55
0
        public static AssetBundleManifest BuildAssetBundles(string output, AssetBundleBuild[] builds, BuildAssetBundleOptions options, BuildTarget target)
        {
            output = Path.GetFullPath(output);

            var tree = new BuildTree();

            foreach (var build in builds)
            {
                foreach (var asset in build.assetNames)
                {
                    tree.AddBuildAsset(asset, build.assetBundleName);
                }
            }

            int slaveCount = Mathf.Max(1, System.Environment.ProcessorCount / 2); //TODO:
            var jobs       = tree.BuildJobs(Mathf.Max(slaveCount, 1), output, options, target);

            AssetBundleManifest[] results = new AssetBundleManifest[jobs.Length];

            bool allFinish = true;

            if (jobs.Length == 0)
            {
                return(null);
            }
            else if (jobs.Length == 1)
            {
                var job = jobs[0];
                File.WriteAllText("build_0.json", JsonUtility.ToJson(job, true));
                if ((options & BuildAssetBundleOptions.DryRunBuild) == 0)
                {
                    results[0] = BuildJob(job);
                }
            }
            else
            {
                //dryrun return null
                if ((options & BuildAssetBundleOptions.DryRunBuild) != 0)
                {
                    return(null);
                }

                List <string> cmds = new List <string>();
                for (int jobID = 0; jobID < jobs.Length; ++jobID)
                {
                    BuildJob job = jobs[jobID];
                    File.WriteAllText(string.Format("build_{0}.json", jobID), JsonUtility.ToJson(job, true));

                    if ((options & BuildAssetBundleOptions.DryRunBuild) == 0)
                    {
                        string cmd = string.Format(" -quit" +
                                                   " -batchmode" +
                                                   " -logfile {0}/log_{1}.txt" +
                                                   //" -projectPath {0} " +
                                                   " -executeMethod MultiProcessBuild.BuildPipeline.BuildJobSlave" +
                                                   " -buildJob {0}/build_{1}.json" +
                                                   " -buildTarget {2}",
                                                   Path.GetFullPath("."),
                                                   jobID,
                                                   target.ToString());
                        cmds.Add(cmd);
                    }
                }

                EditorUserBuildSettings.SwitchActiveBuildTarget(target);

                var exitCodes = MultiProcess.UnityFork(cmds.ToArray(), "building", "waiting for sub process...");
                for (int jobID = 0; jobID < jobs.Length; ++jobID)
                {
                    var ExitCode = exitCodes[jobID];;
                    if (ExitCode != 0)
                    {
                        allFinish = false;
                        UnityEngine.Debug.LogErrorFormat("slave {0} code:{1}", jobID, ExitCode);
                    }
                    else
                    {
                        UnityEngine.Debug.LogFormat("slave {0} code:{1}", jobID, ExitCode);
                        string resultFile = string.Format(string.Format("{0}/result_{1}.json", output, jobID));
                        results[jobID] = JsonUtility.FromJson <AssetBundleManifest>(File.ReadAllText(resultFile));
                    }
                }
            }

            if (allFinish)
            {
                AssetBundleManifest manifest = new AssetBundleManifest();
                manifest.buildTime = 0f;
                List <AssetBundleManifest.AssetBundleBuild> totalBuilds = new List <AssetBundleManifest.AssetBundleBuild>();
                foreach (var result in results)
                {
                    totalBuilds.AddRange(result.builds);
                    manifest.buildTime = Mathf.Max(manifest.buildTime, result.buildTime);
                }
                totalBuilds.Sort((a, b) => { return(a.assetBundleName.CompareTo(b.assetBundleName)); });
                manifest.builds = totalBuilds.ToArray();
                File.WriteAllText(string.Format("{0}/result.json", output), JsonUtility.ToJson(manifest, true));
                UnityEngine.Debug.LogFormat("all slave finish.");
                return(manifest);
            }
            else
            {
                UnityEngine.Debug.LogErrorFormat("some slave error.");
                return(null);
            }
        }
        public bool IsModified(AssetImporter referenceImporter, AssetImporter importer, BuildTarget target, string group)
        {
            var r = referenceImporter as ModelImporter;
            var t = importer as ModelImporter;

            if (r == null || t == null)
            {
                throw new AssetGraphException(string.Format("Invalid AssetImporter assigned for {0}", importer.assetPath));
            }
            return(!IsEqual(t, r));
        }
Exemple #57
0
 public void justBuild()
 {
     _selectTarget = EditorUserBuildSettings.activeBuildTarget;
     doBuild();
 }
Exemple #58
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)
    {
        var lastConfigPath = IPath.Combine(outpath, "Art/Config.json");

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

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

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

            EditorUtility.DisplayProgressBar("分析资源 -" + target,
                                             "分析:" + Path.GetFileNameWithoutExtension(_path) + "   进度:" + curIndex + "/" + paths.Length,
                                             curIndex / paths.Length);
            curIndex++;


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

            //获取被依赖的路径
            var dependsource         = "Assets" + _path.Replace(Application.dataPath, "");
            var allDependObjectPaths = AssetDatabase.GetDependencies(dependsource).ToList();
            dependsource = dependsource.ToLower();
            //
            ManifestItem lastItem = null;
            curManifestConfig.Manifest.TryGetValue(dependsource, out lastItem);
            //last没有或者 uiid不一致被改动,
            //TODO 有改动的要把依赖重新打
            if (lastItem != null && lastItem.UIID == UIID)
            {
                continue;
            }
            else
            {
                Debug.Log("打包:" + dependsource);
            }
            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" || ext == ".dll")
                {
                    continue;
                }
                //
                AssetImporter ai = AssetImporter.GetAtPath(dependPath);
                if (ai == null)
                {
                    BDebug.Log("资源不存在:" + 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();

                ai.assetBundleName    = abname;
                ai.assetBundleVariant = "";

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

                dependAssets.Add(abname);
            }

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


        EditorUtility.ClearProgressBar();
        Debug.Log("本地需要打包资源:" + changeList.Count);
    }
        public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater)
        {
            CSharpCompiler     cSharpCompiler = CSharpLanguage.GetCSharpCompiler(targetPlatform, buildingForEditor, island._output);
            ScriptCompilerBase result;

            if (cSharpCompiler != CSharpCompiler.Microsoft)
            {
                if (cSharpCompiler != CSharpCompiler.Mono)
                {
                }
                result = new MonoCSharpCompiler(island, runUpdater);
            }
            else
            {
                result = new MicrosoftCSharpCompiler(island, runUpdater);
            }
            return(result);
        }
 public static bool TargetIsSupported(BuildTarget target)
 {
     return(target == BuildTarget.StandaloneOSX || target == BuildTarget.StandaloneWindows64 || target == BuildTarget.StandaloneLinux64);
 }