static void PerformBuild() { Console.WriteLine(":: Performing build"); //PlayerSettings.keystorePass = getEnv ("KEYSTORE_PASS", true); //PlayerSettings.keyaliasPass = getEnv ("KEY_ALIAS_PASS", true); var buildTarget = GetBuildTarget(); var buildPath = GetBuildPath(); var buildName = GetBuildName(); var fixedBuildPath = GetFixedBuildPath(buildTarget, buildPath, buildName); if (buildTarget.ToString().ToLower().Contains("android")) { //PlayerSettings.applicationIdentifier = "com.yourcompany.testapp"; PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "com.android.example"); Console.WriteLine(PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android)); //EditorSetup.AndroidSdkRoot = getEnv ("ANDROID_SDK_HOME"); //EditorSetup.JdkRoot = getEnv ("JAVA_HOME"); //EditorSetup.AndroidNdkRoot = getEnv ("ANDROID_NDK_HOME"); //PlayerSettings.Android.keystorePass = "******"; //PlayerSettings.Android.keyaliasName = "testapp"; //PlayerSettings.Android.keyaliasPass = "******"; Console.WriteLine(getEnv("ANDROID_SDK_HOME")); Console.WriteLine(getEnv("JAVA_HOME")); Console.WriteLine(getEnv("ANDROID_NDK_HOME")); } BuildPipeline.BuildPlayer(GetEnabledScenes(), fixedBuildPath, buildTarget, GetBuildOptions()); Console.WriteLine(":: Done with build"); }
protected override void OnPushPlayerSettings(Dictionary <string, object> settingsCache) { #if !UNITY_CLOUD #if UNITY_5_6_OR_NEWER settingsCache["bundleIdentifier"] = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, m_BundleIdentifier); #else settingsCache["bundleIdentifier"] = PlayerSettings.bundleIdentifier; PlayerSettings.bundleIdentifier = m_BundleIdentifier; #endif settingsCache["keystoreName"] = PlayerSettings.Android.keystoreName; PlayerSettings.Android.keystoreName = m_Keystore; settingsCache["keystorePass"] = PlayerSettings.Android.keystorePass; PlayerSettings.Android.keystorePass = m_KeystorePassword; settingsCache["keyaliasName"] = PlayerSettings.Android.keyaliasName; PlayerSettings.Android.keyaliasName = m_KeyAlias; settingsCache["keyaliasPass"] = PlayerSettings.Android.keyaliasPass; PlayerSettings.Android.keyaliasPass = m_KeyAliasPassword; settingsCache["useAPKExpansionFiles"] = PlayerSettings.Android.useAPKExpansionFiles; PlayerSettings.Android.useAPKExpansionFiles = m_SplitApplicationBinary; #endif settingsCache["androidBuildSubtarget"] = EditorUserBuildSettings.androidBuildSubtarget; EditorUserBuildSettings.androidBuildSubtarget = m_DeviceRequirement.TextureCompression; settingsCache["androidBuildSystem"] = EditorUserBuildSettings.androidBuildSystem; EditorUserBuildSettings.androidBuildSystem = m_BuildSystem; settingsCache["exportAsGoogleAndroidProject"] = EditorUserBuildSettings.exportAsGoogleAndroidProject; EditorUserBuildSettings.exportAsGoogleAndroidProject = m_ExportAsGoogleAndroidProject; }
protected override void Reset() { base.Reset(); #if UNITY_5_6_OR_NEWER m_BundleIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS); #else m_BundleIdentifier = PlayerSettings.bundleIdentifier; #endif m_ScriptCallOptimization = PlayerSettings.iOS.scriptCallOptimization; #if HAS_TEAM_ID m_AppleDeveloperTeamId = PlayerSettings.iOS.appleDeveloperTeamID; if (string.IsNullOrEmpty(m_AppleDeveloperTeamId)) { m_AppleDeveloperTeamId = EditorPrefs.GetString(_DefaultiOSAutomaticSignTeamId); } #if HAS_AUTOMATIC_SIGNING m_AutomaticSign = PlayerSettings.iOS.appleEnableAutomaticSigning; #endif #endif m_EnableOnDemandResources = PlayerSettings.iOS.useOnDemandResources; m_EnableAppSlicing = PlayerSettings.iOS.useOnDemandResources; }
//设置info.plist文件 void SetInfo(string pathToBuildProject) { string plistPath = pathToBuildProject + "/Info.plist"; PlistDocument plist = new PlistDocument(); plist.ReadFromString(File.ReadAllText(plistPath)); PlistElementDict plistRoot = plist.root; //指定打包时使用的ProvisioningProfile PlistElementDict dict = plistRoot.CreateDict("provisioningProfiles"); dict.SetString(PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS), PlayerSettings.iOS.iOSManualProvisioningProfileID); plistRoot.SetString("method", PlayerSettings.iOS.iOSManualProvisioningProfileType == ProvisioningProfileType.Development ? "development" : "app-store"); plistRoot.SetString("NSCameraUsageDescription", "需要使用相机"); plistRoot.SetString("NSCalendarsUsageDescription", "需要使用日历"); plistRoot.SetString("NSPhotoLibraryUsageDescription", "需要使用相册"); plistRoot.SetString("NSLocationWhenInUseUsageDescription", "需要访问地理位置"); //龙图SDK设置URL Schemes PlistElementArray URLArray = plistRoot.CreateArray("CFBundleURLTypes"); PlistElementDict elementDict = URLArray.AddDict();; elementDict.SetString("CFBundleURLName", "GoogleID"); elementDict.CreateArray("CFBundleURLSchemes").AddString("com.googleusercontent.apps.837194912770-vt71nif9hiifrdb2hcg2l2ejc94rnloq"); File.WriteAllText(plistPath, plist.WriteToString()); }
private static void LoadConfigIfNecessary() { if (_config != null) { return; } _config = new Configuration(); if (File.Exists(ConfigurationFilePath)) { try { var configurationJson = File.ReadAllText(ConfigurationFilePath); _config = JsonUtility.FromJson <Configuration>(configurationJson); } catch (Exception ex) { Debug.LogErrorFormat("Failed to load {0} due to exception: {1}", ConfigurationFilePath, ex); } } else { Debug.Log("Migrating Instant URL from preference file to JSON config file..."); var packageName = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) ?? "unknown"; var key = "GooglePlayInstant.InstantUrl." + packageName; var oldInstantUrl = EditorPrefs.GetString(key); SaveConfiguration(oldInstantUrl, null, null); EditorPrefs.DeleteKey(key); } }
public static bool IsInstalledAPP() { if (!PXR_ADBTool.GetInstance().IsReady()) { return(false); } string matchedPackageList, error; var packageName = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); string[] packageCheckCommand = new string[] { "-d shell pm list package", packageName }; if (PXR_ADBTool.GetInstance().RunCommand(packageCheckCommand, null, out matchedPackageList, out error) == 0) { if (string.IsNullOrEmpty(matchedPackageList)) { return(false); } if (!matchedPackageList.Contains("package:" + packageName + "\r\n")) { return(false); } string[] dumpPackageInfoCommand = new string[] { "-d shell dumpsys package", packageName }; string packageInfo; if (PXR_ADBTool.GetInstance().RunCommand(dumpPackageInfoCommand, null, out packageInfo, out error) == 0 && !string.IsNullOrEmpty(packageInfo) && packageInfo.Contains(SQP_APK_VERSION)) { return(true); } return(false); } return(false); }
public static bool UninstallAPK() { OVRBundleTool.PrintLog("Uninstalling Application . . ."); OVRADBTool adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath()); if (adbTool.isReady) { string output, error; string appPackagename = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) + GetTransitionApkOptionalIdentifier(); string[] appStartCommand = { "-d shell", "pm uninstall", appPackagename }; if (adbTool.RunCommand(appStartCommand, null, out output, out error) == 0) { OVRBundleTool.PrintSuccess(); OVRBundleTool.PrintLog("App package " + appPackagename + " is uninstalled."); return(true); } OVRBundleTool.PrintError("Failed to uninstall APK."); } else { OVRBundleTool.PrintError(ADB_TOOL_INITIALIZE_ERROR); } return(false); }
// Build and deploy a list of scenes. It's suggested to only build and deploy one active scene that's being modified and // its dependencies such as scenes that are loaded additively public static void BuildDeployScenes(List <OVRBundleTool.EditorSceneInfo> sceneList, bool forceRestart) { externalSceneCache = EXTERNAL_STORAGE_PATH + "/" + PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) + GetTransitionApkOptionalIdentifier() + "/cache/scenes"; for (int i = 0; i < sceneList.Count; i++) { if (!sceneList[i].shouldDeploy) { continue; } sceneList[i].buildStatus = OVRBundleTool.SceneBundleStatus.QUEUED; } BuildSceneBundles(sceneList); if (DeploySceneBundles(sceneList)) { if (forceRestart) { LaunchApplication(); return; } OVRBundleTool.PrintSuccess(); return; } }
/// <summary> /// 預設共通資料(取現在的PlayerSetting) /// PC版的BuildTargetGroup是Standalone /// Unknown是PlayerSetting上面那區 /// 因為Icon設定沒有打算設定PC版 /// 所以只弄預設區塊 /// </summary> private void DefaultSetCommon() { mShowSetInfo = new SDefineSet(); // Names mShowSetInfo.CompanyName = PlayerSettings.companyName; mShowSetInfo.ProductName = PlayerSettings.productName; // Orientation mShowSetInfo.UIOrientation = PlayerSettings.defaultInterfaceOrientation; mShowSetInfo.UseAnimAutor = PlayerSettings.useAnimatedAutorotation; mShowSetInfo.OrienRoatable = new bool[4]; mShowSetInfo.OrienRoatable[0] = PlayerSettings.allowedAutorotateToPortrait; mShowSetInfo.OrienRoatable[1] = PlayerSettings.allowedAutorotateToPortraitUpsideDown; mShowSetInfo.OrienRoatable[2] = PlayerSettings.allowedAutorotateToLandscapeLeft; mShowSetInfo.OrienRoatable[3] = PlayerSettings.allowedAutorotateToLandscapeRight; // Identification /* * PlayerSettings.applicationIdentifier 是取得當下Platform的BundleIdentifier * 要取得特定Platform的Identifier * 要改用PlayerSettings.GetApplicationIdentifier(取得)和PlayerSettings.SetApplicationIdentifier(設置) */ mShowSetInfo.BundleIDStandalone = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Standalone); mShowSetInfo.BundleVer = PlayerSettings.bundleVersion; // Scripting Define Symbols mShowSetInfo.ScriptDefineSymblos = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone); // Icon SDDataMove.GetIconsGroup(BuildTargetGroup.Unknown, ref mUIUseImages.DefaultIcon, ref mShowSetInfo.DefIcons); // Default Icon // --------------------------------------------------------------- }
public static void Run() { string appIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); //This is the default Unity android launcher, however in my experience, it does not work properly. I use monkey launcher instead. //string mainActivity = "com.unity3d.player.UnityPlayerActivity"; //string adbCommand = "shell am start -a android.intent.action.MAIN -n " + appIdentifier + "/" + mainActivity; string adbCommand = "shell monkey -p \"" + appIdentifier + "\" 1"; var process = new ProcessStartInfo(adbPath, adbCommand) { RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, UseShellExecute = false }; var runProcess = Process.Start(process); string result = "Running app " + appIdentifier + ": " + runProcess.StandardOutput.ReadLine() + ": " + runProcess.StandardOutput.ReadToEnd(); result += runProcess.StandardError.ReadToEnd(); if (runProcess.ExitCode != 0) { UnityEngine.Debug.LogError(result); } else { UnityEngine.Debug.Log(result); } }
public virtual bool Initialize(BuildToolLogger buildToolLogger) { // Cache information that is only accessible from the main thread. _isGradleBuild = EditorUserBuildSettings.androidBuildSystem == AndroidBuildSystem.Gradle; _minSdkVersion = PlayerSettings.Android.minSdkVersion; _packageName = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); _versionCode = PlayerSettings.Android.bundleVersionCode; _versionName = PlayerSettings.bundleVersion; _assetPackManifestTransformers = AssetPackManifestTransformerRegistry.Registry.ConstructInstances(); var initializedManifestTransformers = true; foreach (var transformer in _assetPackManifestTransformers) { initializedManifestTransformers &= transformer.Initialize(buildToolLogger); } return(CheckUnityVersion(buildToolLogger) && initializedManifestTransformers && _androidAssetPackagingTool.Initialize(buildToolLogger) && _androidBuilder.Initialize(buildToolLogger) && _jarSigner.Initialize(buildToolLogger) && _bundletool.Initialize(buildToolLogger) && _zipUtils.Initialize(buildToolLogger)); }
private static void AddNotificationServiceExtension(PBXProject project, string path) { #if UNITY_2017_2_OR_NEWER && !UNITY_CLOUD_BUILD var projectPath = PBXProject.GetPBXProjectPath(path); var mainTargetGUID = GetPBXProjectTargetGUID(project); var extensionTargetName = NOTIFICATION_SERVICE_EXTENSION_TARGET_NAME; var exisitingPlistFile = CreateNotificationExtensionPlistFile(path); // If file exisits then the below has been completed before from another build // The below will not be updated on Append builds // Changes would most likely need to be made to support Append builds if (exisitingPlistFile) { return; } var extensionGUID = PBXProjectExtensions.AddAppExtension( project, mainTargetGUID, extensionTargetName, PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS) + "." + extensionTargetName, extensionTargetName + "/" + "Info.plist" // Unix path as it's used by Xcode ); AddNotificationServiceSourceFilesToTarget(project, extensionGUID, path); foreach (var framework in FRAMEWORKS_TO_ADD) { project.AddFrameworkToProject(extensionGUID, framework, true); } // Makes it so that the extension target is Universal (not just iPhone) and has an iOS 10 deployment target project.SetBuildProperty(extensionGUID, "TARGETED_DEVICE_FAMILY", "1,2"); project.SetBuildProperty(extensionGUID, "IPHONEOS_DEPLOYMENT_TARGET", "10.0"); project.SetBuildProperty(extensionGUID, "ARCHS", "$(ARCHS_STANDARD)"); project.SetBuildProperty(extensionGUID, "DEVELOPMENT_TEAM", PlayerSettings.iOS.appleDeveloperTeamID); project.AddBuildProperty(extensionGUID, "LIBRARY_SEARCH_PATHS", "$(PROJECT_DIR)/Libraries/OneSignal/Platforms/iOS"); project.WriteToFile(projectPath); // Add libOneSignal.a to the OneSignalNotificationServiceExtension target var contents = File.ReadAllText(projectPath); // This method only modifies the PBXProject string passed in (contents). // After this method finishes, we must write the contents string to disk InsertStaticFrameworkIntoTargetBuildPhaseFrameworks("libOneSignal", "CD84C25F20742FAB0035D524", extensionGUID, ref contents, project); File.WriteAllText(projectPath, contents); AddOrUpdateEntitlements( path, project, extensionGUID, extensionTargetName, new HashSet <EntitlementOptions> { EntitlementOptions.AppGroups } ); #endif }
static void BuildAndRun() { if (!PXR_ADBTool.GetInstance().CheckADBDevices()) { return; } apkOutputSuccessful = null; syncCancelToken = null; gradleBuildProcess = null; gradleTempExport = Path.Combine(Path.Combine(Application.dataPath, "../Temp"), "PXRGradleTempExport"); gradleExport = Path.Combine(Path.Combine(Application.dataPath, "../Temp"), "PXRGradleExport"); if (!Directory.Exists(gradleExport)) { Directory.CreateDirectory(gradleExport); } var buildResult = UnityBuildPlayer(); if (buildResult.summary.result == UnityEditor.Build.Reporting.BuildResult.Succeeded) { applicationIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); #if UNITY_2019_3_OR_NEWER productName = "launcher"; #else productName = Application.productName; #endif BuildRun(); } }
static void GetApplicationIdentifier() { string applicationIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); string bundleVersion = PlayerSettings.bundleVersion; Debug.Log(applicationIdentifier + "--" + bundleVersion); }
private static void PrebuildProjectSettingUpdate() { // Modify application identifier for transition APK projectDefaultAppIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, projectDefaultAppIdentifier + GetTransitionApkOptionalIdentifier()); // Set VersionCode as a unique identifier for transition APK projectDefaultVersion = PlayerSettings.bundleVersion; PlayerSettings.bundleVersion = TRANSITION_APK_VERSION_NAME; // Modify IL2CPP option as it strips script symbols that are necessary for the scenes at runtime projectScriptImplementation = PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup); if (projectScriptImplementation != ScriptingImplementation.Mono2x) { // Show message in console to make it more clear to developers OVRBundleTool.PrintLog("Build will use Mono as scripting backend."); PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup, ScriptingImplementation.Mono2x); } // Avoid stripping managed code that are necessary for the scenes at runtime projectManagedStrippingLevel = PlayerSettings.GetManagedStrippingLevel(BuildTargetGroup.Android); if (projectManagedStrippingLevel != ManagedStrippingLevel.Disabled) { OVRBundleTool.PrintLog("Build will set Managed Stripping Level to Disabled."); PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, ManagedStrippingLevel.Disabled); } projectStripEngineCode = PlayerSettings.stripEngineCode; if (projectStripEngineCode) { PlayerSettings.stripEngineCode = false; } }
private static void ChangePackageName() { var appId = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); string manifestPath = Path.Combine(pathToTempFolder, MANIFEST_NAME); string manifestText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + $"\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"{appId}\">" + $"\n <application>" + $"\n <provider android:name=\"android.support.v4.content.FileProvider\" android:authorities=\"{appId}.fileprovider\" android:exported=\"false\" android:grantUriPermissions=\"true\" >" + $"\n <meta-data android:name=\"android.support.FILE_PROVIDER_PATHS\" android:resource=\"@xml/filepaths\" />" + $"\n </provider>" + $"\n </application>" + $"\n <uses-permission android:name=\"android.permission.REQUEST_INSTALL_PACKAGES\" />" + $"\n <uses-sdk android:minSdkVersion=\"{GetSDK(PlayerSettings.Android.minSdkVersion, 16)}\" android:targetSdkVersion=\"{GetSDK(PlayerSettings.Android.targetSdkVersion, 29)}\" />" + $"\n</manifest>"; File.WriteAllText(manifestPath, manifestText); string filepathsPath = Path.Combine(pathToTempFolder, PROVIDER_PATHS_NAME); string filepathsText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + $"\n<paths xmlns:android=\"http://schemas.android.com/apk/res/android\">" + $"\n <external-path path=\"Android/data/{appId}\" name=\"files_root\" />" + $"\n <external-path path=\".\" name=\"external_storage_root\" />" + $"\n</paths>"; File.WriteAllText(filepathsPath, filepathsText); lastPackageName = PlayerSettings.applicationIdentifier; int GetSDK(AndroidSdkVersions sdkVersions, int defaultSdk) => sdkVersions == AndroidSdkVersions.AndroidApiLevelAuto ? defaultSdk : (int)sdkVersions; }
public static void LaunchOnAndroid() { #if UNITY_2020_1_OR_NEWER ApplicationIdentifier applicationIdentifier = CurrentConfiguration.GetComponentOrDefault <ApplicationIdentifier>(); string packageName = applicationIdentifier.PackageName; #else //BUG it may not be valid since the application identifier on SBP may be different from the on on PlayerSets string packageName = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); #endif string runTarget = $"\"{packageName}/com.unity3d.player.UnityPlayerActivity\""; ADB adb = ADB.GetInstance(); try { EditorUtility.DisplayProgressBar("Launching", $"Launching {runTarget}", 0.6f); adb.Run(new[] { "shell", "am", "start", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-f", "0x10200000", "-S", "-n", runTarget }, $"Failed to launch {runTarget}"); } catch (Exception ex) { Debug.Log($"Error when launching: {ex}"); } finally { EditorUtility.ClearProgressBar(); } }
public void InitSysConfig() { string tmp = keystoreCnf.bundleIdentifier == "" ? PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Standalone) : keystoreCnf.bundleIdentifier; keystoreCnf.bundleIdentifier = tmp; PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android | BuildTargetGroup.iOS | BuildTargetGroup.Standalone, keystoreCnf.bundleIdentifier); PlayerSettings.bundleVersion = setting.version; if (keystoreCnf.keystore == "") { tmp = PlayerSettings.Android.keystoreName; tmp = tmp.Replace(Environment.CurrentDirectory.Replace("\\", "/"), ""); keystoreCnf.keystore = tmp; } else { PlayerSettings.Android.keystoreName = keystoreCnf.keystore; } tmp = keystoreCnf.keyaliname == "" ? PlayerSettings.Android.keyaliasName : keystoreCnf.keyaliname; PlayerSettings.Android.keyaliasName = keystoreCnf.keyaliname = tmp; tmp = keystoreCnf.keyalipass == "" ? PlayerSettings.Android.keyaliasPass : keystoreCnf.keyalipass; PlayerSettings.Android.keyaliasPass = keystoreCnf.keyalipass = tmp; }
public static bool LaunchApplication() { OVRBundleTool.PrintLog("Launching Application . . . "); OVRADBTool adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath()); if (adbTool.isReady) { string output, error; string appPackagename = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) + GetTransitionApkOptionalIdentifier(); string playerActivityName = "\"" + appPackagename + "/com.unity3d.player.UnityPlayerActivity\""; string[] appStartCommand = { "-d shell", "am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -S -f 0x10200000 -n", playerActivityName }; if (adbTool.RunCommand(appStartCommand, null, out output, out error) == 0) { OVRBundleTool.PrintSuccess(); OVRBundleTool.PrintLog("App package " + appPackagename + " is launched."); return(true); } string completeError = "Failed to launch application. Try launching it manually through the device.\n" + (string.IsNullOrEmpty(error) ? output : error); OVRBundleTool.PrintError(completeError); } else { OVRBundleTool.PrintError(ADB_TOOL_INITIALIZE_ERROR); } return(false); }
private static void OnDomainReload() { var setting = EditorBuildConfigs.GetActiveSettings <BundleIdentifierSetting>(); if (setting == null) { return; } foreach (var buildTargetGroup in BuildTargetGroupUtil.GetValid()) { var currentBundleId = PlayerSettings.GetApplicationIdentifier(buildTargetGroup); if (string.IsNullOrEmpty(setting.bundleId)) { if (string.IsNullOrEmpty(currentBundleId) == false) { setting.bundleId = currentBundleId; break; } } else if (setting.bundleId != currentBundleId) { PlayerSettings.SetApplicationIdentifier(buildTargetGroup, setting.bundleId); } } }
private void DrawAmazonSettingsGUI() { if (m_showAmazonSettings = EditorGUILayout.Foldout(m_showAmazonSettings, "Amazon Device Messaging")) { if (Settings.Instance.PushNotificationsEnabledAmazon = EditorGUILayout.Toggle(m_amazonPushNotificationsEnabledLabel, Settings.Instance.PushNotificationsEnabledAmazon)) { const int width = 260; EditorGUILayout.LabelField(m_packageNameLabel); #if UNITY_5_6_OR_NEWER EditorGUILayout.TextArea(PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android), GUILayout.Width(width)); #else EditorGUILayout.TextArea(PlayerSettings.bundleIdentifier, GUILayout.Width(width)); #endif EditorGUILayout.LabelField(m_androidDebugSignatureMD5Label); EditorGUILayout.TextArea(m_androidDebugSignatureMD5AndSHA256[0], GUILayout.Width(width)); EditorGUILayout.LabelField(m_androidDebugSignatureSHA256Label); EditorGUILayout.TextArea(m_androidDebugSignatureMD5AndSHA256[1], GUILayout.Width(width)); EditorGUILayout.LabelField(m_amazonDebugAPIKeyLabel); string apiKey = EditorGUILayout.TextArea(m_amazonDebugAPIKey, GUILayout.Width(width)); if (apiKey != m_amazonDebugAPIKey) { m_amazonDebugAPIKey = apiKey; Settings.SetAmazonAPIKey(apiKey); } } } EditorGUILayout.Space(); }
private static void PatchPBXProject(string path, bool needLocationFramework, bool addPushNotificationCapability, bool useReleaseAPSEnv) { var pbxProjectPath = PBXProject.GetPBXProjectPath(path); var needsToWriteChanges = false; var pbxProject = new PBXProject(); pbxProject.ReadFromString(File.ReadAllText(pbxProjectPath)); string mainTarget; string unityFrameworkTarget; var unityMainTargetGuidMethod = pbxProject.GetType().GetMethod("GetUnityMainTargetGuid"); var unityFrameworkTargetGuidMethod = pbxProject.GetType().GetMethod("GetUnityFrameworkTargetGuid"); if (unityMainTargetGuidMethod != null && unityFrameworkTargetGuidMethod != null) { mainTarget = (string)unityMainTargetGuidMethod.Invoke(pbxProject, null); unityFrameworkTarget = (string)unityFrameworkTargetGuidMethod.Invoke(pbxProject, null); } else { mainTarget = pbxProject.TargetGuidByName("Unity-iPhone"); unityFrameworkTarget = mainTarget; } // Add necessary frameworks. if (!pbxProject.ContainsFramework(unityFrameworkTarget, "UserNotifications.framework")) { pbxProject.AddFrameworkToProject(unityFrameworkTarget, "UserNotifications.framework", true); needsToWriteChanges = true; } if (needLocationFramework && !pbxProject.ContainsFramework(unityFrameworkTarget, "CoreLocation.framework")) { pbxProject.AddFrameworkToProject(unityFrameworkTarget, "CoreLocation.framework", false); needsToWriteChanges = true; } if (needsToWriteChanges) { File.WriteAllText(pbxProjectPath, pbxProject.WriteToString()); } // Update the entitlements file. if (addPushNotificationCapability) { var entitlementsFileName = pbxProject.GetBuildPropertyForAnyConfig(mainTarget, "CODE_SIGN_ENTITLEMENTS"); if (entitlementsFileName == null) { var bundleIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS); entitlementsFileName = string.Format("{0}.entitlements", bundleIdentifier.Substring(bundleIdentifier.LastIndexOf(".") + 1)); } var capManager = new ProjectCapabilityManager(pbxProjectPath, entitlementsFileName, "Unity-iPhone"); capManager.AddPushNotifications(!useReleaseAPSEnv); capManager.WriteToFile(); } }
static void PerformBuild() { string targetAPK = GetArg("-targetPath"); if (targetAPK == null || targetAPK.Length == 0) { targetAPK = EditorUtility.SaveFilePanel("Choose Location of Built Game", Environment.CurrentDirectory + "/build", "oscillations.apk", "apk"); } AssetDatabase.Refresh(); string[] fixedScenes = { "Assets/Rides/Menu.unity", "Assets/Rides/Shuttlecock-City-Static.unity", "Assets/Rides/Walker-city.unity", "Assets/Rides/HighRoller-City-tiled.unity", "Assets/Rides/Jellyfish-tiled.unity" }; string productName = PlayerSettings.productName; PlayerSettings.productName = "VR Playground 2"; string androidProductID = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "com.mrl.swing"); Debug.Log("Building Oscillate to path: " + targetAPK + ".\nScenes:"); List <string> scenes = new List <string>(fixedScenes); foreach (string nam in scenes) { Debug.Log(nam); } /* for(int c=0;c<20;c++) * { * string name = SceneUtility.GetScenePathByBuildIndex(c); * if(name==null || name.Length==0)break; * scenes.Add(name); * Debug.Log(name); * }*/ BuildPlayerOptions options = new BuildPlayerOptions(); options.scenes = scenes.ToArray(); options.locationPathName = targetAPK; options.target = BuildTarget.Android; options.options = BuildOptions.None; options.targetGroup = BuildTargetGroup.Android; string[] vrSDKs = PlayerSettings.GetVirtualRealitySDKs(BuildTargetGroup.Android); PlayerSettings.SetVirtualRealitySDKs(BuildTargetGroup.Android, new string[] { "Oculus" }); BuildPipeline.BuildPlayer(options); PlayerSettings.SetVirtualRealitySDKs(BuildTargetGroup.Android, vrSDKs); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, androidProductID); PlayerSettings.productName = productName; Debug.Log("Finished build"); }
private static string ApplicationIdentifier() { #if UNITY_5_6_OR_NEWER return(PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android)); #else return(PlayerSettings.bundleIdentifier); #endif }
private static void LaunchMobileClient() { try { // Find ADB tool var sdkRootPath = EditorPrefs.GetString("AndroidSdkRoot"); if (string.IsNullOrEmpty(sdkRootPath)) { Debug.LogError($"Could not find Android SDK. Please set the SDK location in your editor preferences."); return; } var adbPath = Path.Combine(sdkRootPath, "platform-tools", "adb"); EditorUtility.DisplayProgressBar("Launching Mobile Client", "Installing APK", 0.3f); // Find apk to install if (!TryGetApkPath(AbsoluteApkPath, out var apkPath)) { Debug.LogError($"Could not find a built out Android binary in \"{AbsoluteApkPath}\" to launch."); return; } // Ensure an android device/emulator is present if (RedirectedProcess.Run(adbPath, "get-state") != 0) { Debug.LogError("No Android device/emulator detected."); return; } // Install apk on connected phone / emulator RedirectedProcess.Run(adbPath, "install", "-r", apkPath); EditorUtility.DisplayProgressBar("Launching Mobile Client", "Launching Client", 0.9f); // Optional arguments to be passed, same as standalone // Use this to pass through the local ip to connect to var runtimeIp = GdkToolsConfiguration.GetOrCreateInstance().RuntimeIp; var arguments = new StringBuilder(); if (!string.IsNullOrEmpty(runtimeIp)) { arguments.Append($"+{RuntimeConfigNames.ReceptionistHost} {runtimeIp}"); } // Get chosen android package id and launch var bundleId = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); RedirectedProcess.Run(adbPath, "shell", "am", "start", "-S", "-n", $"{bundleId}/com.unity3d.player.UnityPlayerActivity", "-e", "\"arguments\"", $"\\\"{arguments.ToString()}\\\""); EditorUtility.DisplayProgressBar("Launching Mobile Client", "Done", 1.0f); } finally { EditorUtility.ClearProgressBar(); } }
protected override ReturnCode onRun() { try { #if UNITY_EDITOR_OSX string scriptFileName = "xcode-build.sh"; string scriptFilePath = Path.GetFullPath($"Packages/com.cyber1496.unitybuilder/Editor/Impl/Task/Xcode/{scriptFileName}"); string CreateExportOption(string outputPath) { string path = $"{outputPath}/ExportOptions.plist"; var plist = new PlistDocument(); plist.root.SetString("method", "development"); plist.root.SetString("teamID", PlayerSettings.iOS.appleDeveloperTeamID); plist.WriteToFile(path); return(path); } string xcodePath = EditorPrefs.GetString("UnityBuilder.StandardKit.iOS.XcodePath"); string scriptPath = scriptFilePath; string logPath = $"Logs/{helper.BuildTarget}/{Path.GetFileName(scriptPath)}.log"; string outputPath = helper.OutputPath; string exportOptionPlistPath = CreateExportOption(outputPath); var chunk = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS).Split('.'); Utility.ExecuteScript(new ProcessRequest( scriptPath, logPath, new string[] { outputPath, xcodePath, EditorUserBuildSettings.development ? "Debug" : "Release", exportOptionPlistPath }, (result) => { if (result.ExitCode != 0) { throw new Exception($"{scriptPath} exit is {result.ExitCode}."); } } )); return(ReturnCode.Success); #else return(ReturnCode.Success); #endif } catch (Exception ex) { Debug.LogException(ex); if (helper.IsBatchMode) { EditorApplication.Exit(1); } return(ReturnCode.Error); } }
/// <summary> /// 預設IOS資料(取現在的PlayerSetting) /// </summary> private void DefaultSetIOS() { SDIOSSet aTmpSet = new SDIOSSet(); // Resolution and Presentation aTmpSet.RequiresFullScreen = PlayerSettings.iOS.requiresFullScreen; aTmpSet.StatusBarHidden = PlayerSettings.statusBarHidden; aTmpSet.StatusBarStyle = PlayerSettings.iOS.statusBarStyle; aTmpSet.ShowActivityIndicatorOnLoading = PlayerSettings.iOS.showActivityIndicatorOnLoading; // Debugging and crash reporting aTmpSet.ActionOnDotNetUnhandledException = PlayerSettings.actionOnDotNetUnhandledException; aTmpSet.LogObjCUncaughtExceptions = PlayerSettings.logObjCUncaughtExceptions; aTmpSet.EnableCrashReportAPI = PlayerSettings.enableCrashReportAPI; // Identification aTmpSet.BundleIDIOS = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS); aTmpSet.BuildNumber = PlayerSettings.iOS.buildNumber; aTmpSet.AppleEnableAutomaticSigning = PlayerSettings.iOS.appleEnableAutomaticSigning; aTmpSet.AppleDeveloperTeamID = PlayerSettings.iOS.appleDeveloperTeamID; aTmpSet.ProvisioningProfileID = PlayerSettings.iOS.iOSManualProvisioningProfileID; // Configuration aTmpSet.ScriptingBackend = PlayerSettings.GetScriptingBackend(BuildTargetGroup.iOS); aTmpSet.ApiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(BuildTargetGroup.iOS); aTmpSet.TargetDevice = PlayerSettings.iOS.targetDevice; aTmpSet.SDKVersion = PlayerSettings.iOS.sdkVersion; aTmpSet.TargetOSVersionString = PlayerSettings.iOS.targetOSVersionString; aTmpSet.PrepareIOSForRecording = SDDataMove.GetBoolPlayerSetting("Prepare IOS For Recording"); aTmpSet.RequiresPersistentWiFi = PlayerSettings.iOS.requiresPersistentWiFi; aTmpSet.AppInBackgroundBehavior = PlayerSettings.iOS.appInBackgroundBehavior; aTmpSet.Architecture = PlayerSettings.GetArchitecture(BuildTargetGroup.iOS); // Optimization aTmpSet.ScriptCallOptimizationLevel = PlayerSettings.iOS.scriptCallOptimization; aTmpSet.StripEngineCode = PlayerSettings.stripEngineCode; aTmpSet.StripLevel = PlayerSettings.strippingLevel; // Scripting Define Symbols aTmpSet.ScriptDefineSymblos = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS); // Icon aTmpSet.IconOverride = true; SDDataMove.GetIconsGroup(BuildTargetGroup.iOS, ref mUIUseImages.IosIcons, ref aTmpSet.DefIcons); aTmpSet.PrerenderedIcon = PlayerSettings.iOS.prerenderedIcon; // Splash Images int aEmumTotal = Enum.GetNames(typeof(eMobileSplashScreen)).Length; mUIUseImages.IOSSplashImages = new Texture2D[aEmumTotal]; aTmpSet.SplashImages = new string[aEmumTotal]; for (int i = 0; i < aEmumTotal; i++) { aTmpSet.SplashImages[i] = SDDataMove.GetSplashScreenPath((eMobileSplashScreen)i, ref mUIUseImages.IOSSplashImages[i]); } //------------------------------------------------- // Unity5 New aTmpSet.GraphicsType = PlayerSettings.GetGraphicsAPIs(BuildTarget.iOS); // Set Down mShowSetInfo.IOSSet = aTmpSet; }
/// <summary> /// Android手机通过数据线连接Unity,需要重置连接,然后在Unity Console中显示log,Unity Profiler可以连接手机。(适用于PC;mac没有测试) /// 打包时需要勾选(PlayerSetting-->Enable Internal Profiler),(BuildSetting-->Development Build),(BuildSetting-->Autoconnect Profiler)。 /// 设备链接后电脑后启动app,然后点击Reset。 /// 需要配置adb的环境变量 /// </summary> static void AndroidProfilerReset() { string bundleId = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); Debug.Log("bundleId:" + bundleId); if (!string.IsNullOrEmpty(bundleId)) { string command = "adb forward tcp:34999 localabstract:Unity-" + bundleId; ProcessTask.RunCmdAsync(command); } }
public override RunStepResult Start(BuildSettings settings) { var artifact = BuildArtifacts.GetBuildArtifact <BuildArtifactDesktop>(settings); var fileName = artifact.OutputTargetFile.FullName; if (Path.GetExtension(fileName) != ".apk") { return(Failure(settings, $"Expected .apk in path, but got '{fileName}'.")); } var path = $"\"{Path.GetFullPath(fileName)}\""; #if UNITY_ANDROID EditorUtility.DisplayProgressBar("Installing", $"Installing {path}", 0.3f); var adb = ADB.GetInstance(); try { adb.Run(new[] { "install", "-r", "-d", path }, $"Failed to install '{fileName}'"); } catch (Exception ex) { EditorUtility.ClearProgressBar(); return(Failure(settings, ex.Message)); } UnityEngine.Debug.Log($"{path} successfully installed."); var runTarget = $"\"{PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android)}/com.unity3d.player.UnityPlayerActivity\""; EditorUtility.DisplayProgressBar("Launching", $"Launching {runTarget}", 0.6f); try { adb.Run(new[] { "shell", "am", "start", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-f", "0x10200000", "-S", "-n", runTarget }, $"Failed to launch {runTarget}"); } catch (Exception ex) { EditorUtility.ClearProgressBar(); return(Failure(settings, ex.Message)); } UnityEngine.Debug.Log($"{runTarget} successfully launched."); EditorUtility.ClearProgressBar(); return(Success(settings, new RunInstanceAndroid())); #else return(Failure(settings, $"Active Editor platform has to be set to Android.")); #endif }
public string GetFolderName() { StringBuilder s = new StringBuilder(nameFormat); s.Replace("{name}", Application.productName); s.Replace("{package}", PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.WebGL)); s.Replace("{version}", Application.version); s.Replace("{bundle}", PlayerSettings.Android.bundleVersionCode.ToString()); s.Replace("{date}", DateTime.Now.ToString(dateTimeFormat)); return(s.ToString()); }