20211007のUnityに関する記事は4件です。

[Unity] iOS NativePluginの実装の仕方

はじめに Androidに引き続き、iOS側でもNativePluginの作成方法をまとめました。 ここでは、UnityでiOSのNativeアラートを表示させるまでの忘却録です。 Unity向けのiOS Pluginは作り方は人によって違うと思いますが、 今回は『UnityのiOSビルド結果であるXcodeプロジェクト上からコードを編集しました。』 もっと効率の良いやり方があればご教授下さい><; Android版↓ 準備 macOS Catalina: 10.15.7 Unity 2018.4.19f Xcode12.4 Swift4.0 UnityとiOS Pluginの構成 Unityから書き出されるiOS関連のファイルはObjective-CベースなのでSwiftを呼び出す設定が必要です。 SwiftからObjective-Cのクラスに呼ぶには、宣言されてるヘッダーファイルを特定のヘッダーファイルでimportして使用します。 今回はObjective-C++のコードを経由させます。 呼び出しの簡易図は下記。 UnityのC#がインターフェース(.csファイル) ↑↓ ↓↑ iOSネイティブ Objective-C++ Cインターフェース(.mmファイル) ↓↑ ↓↑ iOSネイティブ Swiftコード(.swiftファイル) Unity側の対応(呼び出し方法)サンプル ボタンを押下してアラート表示は、Androidの時の対応と同様な構成にしています。 ここでのポイントは下記です。 ①、[DllImport("__Internal")]属性を付けること。 ネイティブプラグイン参照 ButtonView.cs using System.Runtime.InteropServices; using UnityEngine; public class ButtonView : MonoBehaviour { #if UNITY_IOS && !UNITY_EDITOR [DllImport("__Internal")] private static extern void _showAlert(); #endif public void ShowNativeDialog() { #if UNITY_IOS && !UNITY_EDITOR _showAlert(); #endif } } Unity上でSwiftファイル、Objective-C++のファイルを準備 Assets→Plugin→iOSディレクトリが無ければ作成します。 ここにNativePluginのファイルを置きます。 AlertPlugin.swift、AlertPlugin.mmファイルを作成。中身は空です。 ビルド周りのEditor拡張が必要 やることは下記です。 ①、Swiftのバージョン指定する(今回はSwift4.0) ②、Objective-C Bridging Headerの設定 ③、Objective-C Generated Interface Header Nameの設定 上記を設定していきますが、便利なPluginが既に用意されてるのでこちらを使用していきます。 ビルド時に自動で設定してくれます。ありがたや! unity-swift.unitypackageをDownloadしてUnityへimportします。 Assets→Import Package→Custom PackageでImportします。 Swiftのバージョン指定を追加します。PostProcessor.csを改修します。 SWIFT_VERSIONで4.0を下記で指定して追加 PostProcessor.cs using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using UnityEditor.iOS.Xcode; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace UnitySwift { public static class PostProcessor { [PostProcessBuild] public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath) { if(buildTarget == BuildTarget.iOS) { // So PBXProject.GetPBXProjectPath returns wrong path, we need to construct path by ourselves instead // var projPath = PBXProject.GetPBXProjectPath(buildPath); var projPath = buildPath + "/Unity-iPhone.xcodeproj/project.pbxproj"; var proj = new PBXProject(); proj.ReadFromFile(projPath); var targetGuid = proj.TargetGuidByName(PBXProject.GetUnityTargetName()); //// Configure build settings proj.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO"); proj.SetBuildProperty(targetGuid, "SWIFT_OBJC_BRIDGING_HEADER", "Libraries/UnitySwift/UnitySwift-Bridging-Header.h"); proj.SetBuildProperty(targetGuid, "SWIFT_OBJC_INTERFACE_HEADER_NAME", "unityswift-Swift.h"); proj.AddBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks"); proj.AddBuildProperty(targetGuid, "SWIFT_VERSION", "4.0"); proj.WriteToFile(projPath); } } } } ビルドしてiOSプロジェクトを書き出す File→Build Settings→Buildで書き出されるディレクトリ名を決めて作成。 Unity-iPhone.xcodeprojをXcodeで展開します。 Xcode上での作業 Xcodeを開くと下記のようなディレクトリ構造になっています。 AlertのコードはUnity-iPhone→Libraries→Plugins→iOSに内包されてます。 Unityで追加したファイルはLibrariesに入るみたいです。 先程、ビルド周りのEditer拡張で指定した下記はこちらに設定されていますので、確認します。 ①、Swiftのバージョン指定する(今回はSwift4.0) ②、Objective-C Bridging Headerの設定 ③、Objective-C Generated Interface Header Nameの設定 Swiftコードは下記です。ここで必要なことは下記です。 ①、クラスは NSObject を継承する ②、クラスのスコープを public にする ※ public にするのは、Objective-C++から直接呼び出したいクラスおよびメソッドだけでも良い。 ③、メソッドに@objcを付ける AlertPlugin.swift public class AlertPlugin : NSObject { @objc static func showAlert() { let alertView = UIAlertController(title: "Title", message: "AlertMessage", preferredStyle: UIAlertController.Style.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:nil) let cancelButton = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler:nil) alertView.addAction(okAction) alertView.addAction(cancelButton) UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil) } } Objective-C++コードです。ここでのポイントは、下記です。 ①、extern "C"宣言でCインターフェイスを作成。 ②、Objective-C Generated Interface Header Nameで設定しているunityswift-Swift.hをimportすること。 これをimportするとObjective-C++のクラスのように呼び出すことができる。 AlertPlugin.mm #import "unityswift-Swift.h" extern "C" { void _showAlert() { [AlertPlugin showAlert]; } } 実機確認 成果物 参考
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Unity x Androidビルドで「Failed to update Android SDK package list. See the Console for details.」

2ヶ月ぶりに、久々Androidビルドをしたらこんな下記エラーが。 Failed to update Android SDK package list. See the Console for details. 試したこと UnityHubのAndroidモジュールが正しいかチェック Android SDKが新しいかチェック。 UnityHubのモジュールを使っているので、下記をチェック。 問題なさそう、念の為Unity2019をつかっていたので最新版のUnity2019.4.30f1を入れ直し+Androidのモジュールも 下記画像のようにした。 が、結局改善されず。 Javaを入れ直す Javaを入れ直すという方法がいくつか見つかりました。 新しめのUnityは無料で商用OKなOpenJDKを使っている認識だったので関係ないのでは、 と思って、試しに普通のJDKを入れなおしなど行いましたが改善せず。。 改善した方法 色々設定を触った結果、以下キャプチャの Unity > Prerences のExternal Toolsの JDK Android SDK Android NDK のチェック外して、反映させてUnity閉じる。 次に、再度チェックをいれなおす事で改善しましたw ※Unity再起動や、NDKは関係ないかもですが、一応チェック入れおなしました。 環境 macOS BigSur 11.4 Unity 2019.4.30f1 (UnityHub) AdmobSDK+FirebaseSDK投稿時点最新版 参考にさせて頂いたサイト様
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

UnityでAndroidビルド時エラー対応メモ

licencesエラー エラー内容 CommandInvokationFailure: Gradle build failed. /Applications/Unity/Hub/Editor/2019.2.17f1/PlaybackEngines/AndroidPlayer/Tools/OpenJDK/MacOS/bin/java -classpath "/Applications/Unity/Hub/Editor/2019.2.17f1/PlaybackEngines/AndroidPlayer/Tools/gradle/lib/gradle-launcher-5.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease" stderr[ FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'gradleOut'. > Failed to install the following Android SDK packages as some licences have not been accepted. platforms;android-27 Android SDK Platform 27 To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager. Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html Using Android SDK: /Applications/Unity/Hub/Editor/2019.2.17f1/PlaybackEngines/AndroidPlayer/SDK * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 4s ] stdout[ > Configure project : File /Users/user_name/.android/repositories.cfg could not be loaded. Checking the license for package Android SDK Platform 27 in /Applications/Unity/Hub/Editor/2019.2.17f1/PlaybackEngines/AndroidPlayer/SDK/licenses Warning: License for package Android SDK Platform 27 not accepted. ] exit code: 1 UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.AndroidJavaTools.RunJava (System.String args, System.String workingdir, System.Action`1[T] progress, System.String error) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <502f1b7df2d7430696af84c6f02852ed>:0) Rethrow as GradleInvokationException: Gradle build failed UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <502f1b7df2d7430696af84c6f02852ed>:0) Rethrow as BuildFailedException: Exception of type 'UnityEditor.Build.BuildFailedException' was thrown. UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <502f1b7df2d7430696af84c6f02852ed>:0) UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at /Users/builduser/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:281) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) (at /Users/builduser/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179) 対応 cd ~/Library/Android/sdk/tools/bin ./sdkmanager --licenses
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【unity】clusterハロウィンかぼちゃを光らせてみたよぉ

環境メモ ⭐️Mac Book Pro(Mac OS Catalina) ⭐️Unity 2019.4.22f1 ↓↓↓完成内容 ?Unity ?☀️Blenderで作った3D?ハロウィン?かぼちゃをUnityで✨光らせてみたよぉ✨??あやしい?月の夜空?も加わって?なんだか?ハロウィンっぽく不気味な雰囲気になってきたぞぉ??ハロウィン?VR作るぞ?↓↓手順書https://t.co/5TppaJL9rs#cluster #Unity pic.twitter.com/LAi3IYtnrY— non (@nonnonkapibara) October 6, 2021 clusterのオフィシャルサイト「Creators Guid」に載っているPostProcessingの設定をやってみました。 以下、clusterのオフィシャルサイトの手順書 PostProcessingを使ってワールドをより魅力的にする https://creator.cluster.mu/2020/04/01/howto-postprocessing/ PostProcessingをインストールする 私は、「Cluster Creator Kit」を使っているので、PostProcessingをインストールする必要がありました。 「ClusterCreatorKitSample-master」を使っている場合は、PostProcessingのインストールは不要です。 Creator Kitで利用可能なバージョンについてはclusterドキュメントPost Processingページを参照。 現時点 2020.10.08時点では、「Version 2.3.0」でした。 https://clustervr.gitbook.io/creatorkit/world/asset#post-processing Post Processingを設定する マテリアルを光らせる設定 完成!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む