Unity/Native連携/Kotlin連携
提供: 初心者エンジニアの簡易メモ
はじめに
以下を確認 Unity/Native連携/Android連携 [ショートカット]
javaをkotlinにする場合
UnityRenkei.javaを削除し、UnityRenkei.ktを追加する
UnityRenkei.kt
package com.example.mylibrary import android.util.Log class UnityRenkei { companion object { @JvmStatic fun teststatic(flag: Boolean): Boolean { return flag } @JvmStatic fun teststrstatic(message: String): String { return "Static received: $message" } @JvmStatic fun testnumberstatic(num: Int): Int { return num + 10 } } fun test(flag: Boolean): Boolean { return flag } fun testexec() { Log.i("test", "testexec") } }
プロジェクト直下のbuild.gradleにbuildscriptを追加
buildscript { ext.kotlin_version = "1.8.10" repositories { google() mavenCentral() } dependencies { classpath "com.android.tools.build:gradle:8.1.0" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } plugins { id 'com.android.application' version '8.1.0' apply false id 'com.android.library' version '8.1.0' apply false id 'org.jetbrains.kotlin.android' version '1.8.10' apply false }
mylibrary/build.gradleを以下の通り修正
plugins { id 'com.android.library' id 'org.jetbrains.kotlin.android' } android { namespace 'com.example.mylibrary' compileSdk 34 defaultConfig { minSdk 24 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles "consumer-rules.pro" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } } dependencies { implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.8.0' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" }
"NoClassDefFoundError"エラーが出る場合
エラー詳細
Error Unity AndroidJavaException: java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/jvm/internal/Intrinsics; Error Unity java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/jvm/internal/Intrinsics;
対策方法
ProjectSettingsのAndroidのCustomMainGradleTemplateをチェック
Assets/Plugins/Android/mainTemplate.gradle に以下を追加
buildscript { ext.kotlin_version = '1.8.0' repositories { google() mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'com.android.library' apply plugin: 'kotlin-android' dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Kotlinランタイムを追加 }