1인 개발 게임 (Unity)/UNITY

[Unity6] kakao sdk로 login 로그인 기능 만들기 ios/ android

Z46 2025. 11. 8. 11:47

우선 참고한 글은 다음과 같다!!!

 

android 

=>

1)https://drive.google.com/file/d/1ZYCrJ1WRtq2ioTIsNnPo3M0jQJgezzSM/view

 

2) 오류

https://codehunter.tistory.com/entry/카카오-로그인

 

그러나 나는 unity6을 사용하여서 그런지 위의 방법과 호환이 되지 않았다.

그래서 짜잔~ unity 6에서 kakao sdk2 버전을 통해서 native sdk지만 unity plugin으로 작동하게 하기! 를 위한 

필요한 스크립트들을 적어주고 가겠다. 이 스크립트들을 plugins/android 밑의 폴더에 넣어주면 

kakao login 기능을 부담없이 쓸 수 있을 것이다 !

하지만 google signin sdk를 위한 코드도 섞여 있는 점은 고려해주세요!

 

1. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="당신의 유니티 프로젝트 이름(com.DefaulCompany.프로젝트이름 형식)"> 

    <uses-permission android:name="android.permission.INTERNET" />

  <application
      android:name="당신의 유니티 프로젝트 이름.GlobalApplication">

    <!-- ✅ GameActivity 엔트리 포인트 -->
    <activity
        android:name="com.unity3d.player.UnityPlayerGameActivity"
        android:enabled="true"
        tools:replace="android:enabled"
        android:exported="true"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:hardwareAccelerated="true"
        android:usesCleartextTraffic ="true"
        android:theme="@style/BaseUnityGameActivityTheme"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density"
        tools:node="replace">

      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      
      <intent-filter>
                      <action android:name="android.intent.action.VIEW" />
                      <category android:name="android.intent.category.DEFAULT" />
                      <category android:name="android.intent.category.BROWSABLE" />
                      
                      <!-- 여기에 실제 네이티브 앱 키 입력 -->
                      <data android:host="oauth"
                            android:scheme="kakao당신의 네이티브 키" />
                  </intent-filter>


                  <meta-data android:name="com.kakao.sdk.AppKey" android:value="당신의 네이티브 키" />
                  
     
      <!-- GameActivity/Activity 공통으로 쓰는 메타데이터 -->
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <!-- GameActivity는 네이티브 lib 이름 명시 (Unity 기본은 'game') -->
      <meta-data android:name="android.app.lib_name" android:value="game" />
    </activity>

<activity 
            android:name="com.kakao.sdk.auth.AuthCodeHandlerActivity"
            android:exported="true"
            android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data
                    android:host="oauth"
                    android:scheme="당신의 네이티브 키" />
            </intent-filter>
        </activity>
        
        <activity
            android:name="com.kakao.sdk.auth.CustomTabLauncherActivity"
            android:exported="false"
            android:launchMode="singleTask" />



  </application>
</manifest>

 

2. baseProjectTemplate.gradle

plugins {
    // If you are changing the Android Gradle Plugin version, make sure it is compatible with the Gradle version preinstalled with Unity
    // See which Gradle version is preinstalled with Unity here https://docs.unity3d.com/Manual/android-gradle-overview.html
    // See official Gradle and Android Gradle Plugin compatibility table here https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
    // To specify a custom Gradle version in Unity, go do "Preferences > External Tools", uncheck "Gradle Installed with Unity (recommended)" and specify a path to a custom Gradle version
    id 'com.android.application' version '8.7.2' apply false
    id 'com.android.library' version '8.7.2' apply false
    id 'org.jetbrains.kotlin.android' version '2.1.0' apply false
}

tasks.register('clean', Delete) {
    delete rootProject.layout.buildDirectory
}

 

3. GlobalApplication.kt //초기화 용

package 당신의 유니티 프로젝트 이름
import android.app.Application
import com.kakao.sdk.common.KakaoSdk

class GlobalApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        KakaoSdk.init(this, "당신의 네이티브 키")
    }
}

 

4.gradleTemplate.properties

org.gradle.jvmargs=-Xmx**JVM_HEAP_SIZE**M
org.gradle.parallel=true

unityStreamingAssets=**STREAMING_ASSETS**
# Android Resolver Properties Start
android.useAndroidX=true
android.enableJetifier=true

# Android Resolver Properties End
**ADDITIONAL_PROPERTIES**

 

5.mainTemplate.gradle

apply plugin: 'com.android.library'
apply from: '../shared/keepUnitySymbols.gradle'
apply from: '../shared/common.gradle'
**APPLY_PLUGINS**

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
// Android Resolver Dependencies Start
    implementation 'com.google.android.gms:play-services-auth:16+' // Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml:10
    implementation 'com.google.android.gms:play-services-base:18.9.0' // Assets/Firebase/Editor/AppDependencies.xml:17
    implementation 'com.google.firebase:firebase-analytics:23.0.0' // Assets/Firebase/Editor/FunctionsDependencies.xml:15
    implementation 'com.google.firebase:firebase-app-unity:13.4.0' // Assets/Firebase/Editor/AppDependencies.xml:22
    implementation 'com.google.firebase:firebase-auth:24.0.1' // Assets/Firebase/Editor/AuthDependencies.xml:13
    implementation 'com.google.firebase:firebase-auth-unity:13.4.0' // Assets/Firebase/Editor/AuthDependencies.xml:20
    implementation 'com.google.firebase:firebase-common:22.0.1' // Assets/Firebase/Editor/AppDependencies.xml:13
    implementation 'com.google.firebase:firebase-firestore:26.0.2' // Assets/Firebase/Editor/FirestoreDependencies.xml:13
    implementation 'com.google.firebase:firebase-firestore-unity:13.4.0' // Assets/Firebase/Editor/FirestoreDependencies.xml:20
    implementation 'com.google.firebase:firebase-functions:22.0.1' // Assets/Firebase/Editor/FunctionsDependencies.xml:13
    implementation 'com.google.firebase:firebase-functions-unity:13.4.0' // Assets/Firebase/Editor/FunctionsDependencies.xml:20
    implementation 'com.google.signin:google-signin-support:1.0.4' // Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml:9
    implementation 'com.kakao.sdk:v2-user:2.22.0' //카카오 로그인을 위한 구글 의존성
// Android Resolver Dependencies End
**DEPS**}

// Android Resolver Exclusions Start
/*android {
    namespace "com.unity3d.player"
    ndkPath "**NDKPATH**"
    ndkVersion "**NDKVERSION**"
  packaging {
      exclude ('/lib/armeabi/*' + '*')
      exclude ('/lib/mips/*' + '*')
      exclude ('/lib/mips64/*' + '*')
      exclude ('/lib/x86/*' + '*')
      exclude ('/lib/x86_64/*' + '*')
  }
}*/
// Android Resolver Exclusions End
android {
    namespace "당신의 유니티 프로젝트 이름"
    ndkPath "**NDKPATH**"
    ndkVersion "**NDKVERSION**"
  packaging {
      exclude ('/lib/armeabi/*' + '*')
      exclude ('/lib/mips/*' + '*')
      exclude ('/lib/mips64/*' + '*')
      exclude ('/lib/x86/*' + '*')
      exclude ('/lib/x86_64/*' + '*')
  }
    compileSdk **APIVERSION**
    buildToolsVersion = "**BUILDTOOLS**"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
   
    }

    defaultConfig {
**DEFAULT_CONFIG_SETUP**
        minSdk **MINSDK**
        targetSdk **TARGETSDK**
        ndk {
            debugSymbolLevel **DEBUGSYMBOLLEVEL**
            abiFilters **ABIFILTERS**
        }
        versionCode **VERSIONCODE**
        versionName '**VERSIONNAME**'
        consumerProguardFiles 'proguard-unity.txt'**USER_PROGUARD**
    }

    lint {
        abortOnError false
    }

    androidResources {
        noCompress = **BUILTIN_NOCOMPRESS** + unityStreamingAssets.tokenize(', ')
        ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~"
    }**PACKAGING**
}**REPOSITORIES**
**IL_CPP_BUILD_SETUP**
**SOURCE_BUILD_SETUP**
**EXTERNAL_SOURCES**

 

6. settingsTemplate.gradle

pluginManagement {
    repositories {
        **ARTIFACTORYREPOSITORY**
        gradlePluginPortal()
        google()
        mavenCentral()
    }
    plugins {
    id("org.jetbrains.kotlin.android") version "2.0.21"   // ← 여기서 버전 고정
  }
}

include ':launcher', ':unityLibrary'
**INCLUDES**

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://devrepo.kakao.com/nexus/content/groups/public/") }
       
// Android Resolver Repos Start
        def unityProjectPath = $/file:///**DIR_UNITYPROJECT**/$.replace("\\", "/")
        maven {
            url (unityProjectPath + "/Assets/GeneratedLocalRepo/Firebase/m2repository") // Assets/Firebase/Editor/AppDependencies.xml:22, Assets/Firebase/Editor/AuthDependencies.xml:20, Assets/Firebase/Editor/FirestoreDependencies.xml:20, Assets/Firebase/Editor/FunctionsDependencies.xml:20
        }
        maven {
            url (unityProjectPath + "/Assets/GoogleSignIn/Editor/m2repository") // Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml:9
        }
        mavenLocal()
// Android Resolver Repos End
        flatDir {
            dirs "${project(':unityLibrary').projectDir}/libs"
        }
    }
}

 

7.UKakao.kt

package 당신의 유니티 패키지 이름
import android.util.Log
import com.kakao.sdk.auth.model.OAuthToken
import com.kakao.sdk.common.model.ClientError
import com.kakao.sdk.common.model.ClientErrorCause
import com.kakao.sdk.user.UserApiClient
import com.unity3d.player.UnityPlayer

class UKakao {

    val context = UnityPlayer.currentActivity
    fun KakaoLogin() {
        val callback: (OAuthToken?, Throwable?) -> Unit = { token, error ->
            if (error != null) {
                Log.e("UnityLog", "카카오계정으로 로그인 실패", error)
            } else if (token != null) {
                Log.i("UnityLog", "카카오계정으로 로그인 성공 ${token.accessToken}")
            }
        }

        if (UserApiClient.instance.isKakaoTalkLoginAvailable(context)) {
            UserApiClient.instance.loginWithKakaoTalk(context) { token, error ->
                if (error != null) {
                    Log.e("UnityLog", "카카오톡으로 로그인 실패", error)

                    if (error is ClientError && error.reason == ClientErrorCause.Cancelled) {
                        return@loginWithKakaoTalk
                    }

                    // 카카오톡에 연결된 카카오계정이 없는 경우, 카카오계정으로 로그인 시도
                    UserApiClient.instance.loginWithKakaoAccount(context, callback = callback)
                } else if (token != null) {
                    Log.i("UnityLog", "카카오톡으로 로그인 성공 ${token.accessToken}")
                }
            }
        } else {
            UserApiClient.instance.loginWithKakaoAccount(context, callback = callback)
        }
    }










}

8. kakaoSignin.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class kakaoSignin : MonoBehaviour
{
    private AndroidJavaObject _androidJavaObject;
    void Start()
    {
        _androidJavaObject = new AndroidJavaObject("당신의 유니티 프로젝트 이름.UKakao");
    }
    //카카오 로그인
    public void OnSignInKakao()
    {
        _androidJavaObject.Call("KakaoLogin");
    }
}