Unity

Unity에서 Google Sheets API(OAuth 2.0)를 적용하여 스프레드시트 공유 없이 안전하게 데이터 가져오는 방법

정보처리마법사 2025. 2. 17. 01:05
반응형

Unity에서 Google Sheets API(OAuth 2.0)를 적용하여 스프레드시트 공유 없이 안전하게 데이터 가져오는 방법

 

오늘 Unity 프로젝트에서 **Google Sheets API(OAuth 2.0)**를 적용했습니다.
처음에는 기존 방식인 API 키를 사용하려 했으나, API 키 방식은 스프레드시트를 공개해야만 데이터를 가져올 수 있는 문제가 있었습니다.
그래서 OAuth 2.0 방식을 사용하여 스프레드시트를 공개하지 않고도 데이터를 가져오는 방법을 적용했습니다.

하지만 적용하는 과정에서 NuGet 패키지를 설치했음에도 불구하고 DLL을 찾을 수 없는 문제를 겪었고, 결국 직접 DLL을 추가하여 해결했습니다.
이 과정을 처음부터 끝까지 정리해 보겠습니다.

 

🔹 1. 왜 Google Sheets API(OAuth 2.0)를 사용했는가?

✅ 기존에는 API 키 방식(API_KEY)을 사용했지만, 스프레드시트를 "모든 사용자 보기 가능"으로 설정해야만 API가 데이터를 가져올 수 있음
✅ 하지만, 중요한 데이터가 포함된 경우 보안상 스프레드시트를 공개하고 싶지 않음
✅ 따라서 OAuth 2.0 인증을 통해 서비스 계정을 사용하여 "비공개 상태에서도" 데이터를 가져오는 방식 적용

 

🔹 2. Google Sheets API(OAuth 2.0) 설정 과정

1️⃣ Google Cloud Console에서 새 프로젝트 생성
2️⃣ Google Sheets API & Google Drive API 활성화
3️⃣ 서비스 계정 생성 및 JSON 키 다운로드
4️⃣ Google Sheets에서 서비스 계정 이메일을 편집자로 초대
5️⃣ Unity 프로젝트에 JSON 키 파일 추가

이 과정까지는 비교적 문제없이 진행되었습니다.
하지만, Unity에서 Google.Apis.Sheets.v4 관련 네임스페이스를 찾을 수 없는 문제가 발생했습니다.

 

🔹 3. Unity에서 Google API 패키지 설치 & 오류 발생

✅ 처음에는 NuGet 패키지를 사용하여 Google Sheets API 관련 패키지 설치
✅ Install-Package Google.Apis.Sheets.v4 명령어로 설치했지만, Unity와 Visual Studio에서 참조 오류 발생
"Google 네임스페이스를 찾을 수 없습니다", "SheetsService를 찾을 수 없습니다" 등의 오류가 발생

결국, NuGet으로 패키지를 설치해도 Unity에서 제대로 인식되지 않는 문제였음.


🔹 4. 해결 방법 – DLL을 직접 추가

🚀 NuGet 패키지가 Unity에서 인식되지 않을 경우, DLL을 직접 추가해야 합니다.

✅ (1) 필요한 DLL을 수동으로 찾기

1️⃣ NuGet 패키지 폴더에서 필요한 DLL을 직접 복사

  • 기본 위치: C:\Users\사용자이름\.nuget\packages
    2️⃣ 아래 4개의 파일을 찾아 Unity 프로젝트에 추가
 
Google.Apis.dll
Google.Apis.Core.dll
Google.Apis.Auth.dll
Google.Apis.Sheets.v4.dll

✅ (2) Unity에서 DLL을 추가

1️⃣ Unity 프로젝트의 Assets/Plugins/ 폴더에 .dll 파일 복사

 
📂 Unity Project
 ├── 📂 Assets
 │   ├── 📂 Plugins   👈 **여기에 복사**
 │   │   ├── Google.Apis.dll
 │   │   ├── Google.Apis.Core.dll
 │   │   ├── Google.Apis.Auth.dll
 │   │   ├── Google.Apis.Sheets.v4.dll

✅ (3) Visual Studio에서 참조 추가

1️⃣ Visual Studio 솔루션 탐색기에서 "참조(References)" 마우스 우클릭 → "참조 추가" 선택
2️⃣ "찾아보기(Browse)"에서 Assets/Plugins/ 폴더의 .dll 파일을 추가
3️⃣ "확인(OK)"을 누르고 다시 빌드

🚀 이제 Visual Studio에서도 참조 오류가 사라지고, Unity에서도 정상적으로 Google Sheets API를 사용할 수 있었습니다! 🎉

 

🔹 5. Unity에서 Google Sheets API(OAuth 2.0) 적용 코드

🔹 Google Sheets API를 Unity에서 호출하여 데이터를 가져오는 코드 예제

using UnityEngine;
using UnityEditor;
using Unity.EditorCoroutines.Editor;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using System.Collections;
using System.IO;
using System.Threading.Tasks;

public class GoogleSheetsDataLoader
{
    private static string spreadsheetId = "YOUR_SPREADSHEET_ID"; // 구글 시트 ID
    private static string[] sheetNames = new string[] { "Sheet1", "Sheet2" }; // 탭 이름 목록
    private static string jsonKeyFileName = "google-service-key.json"; // JSON 키 파일명
    private static SheetsService sheetsService;

    [MenuItem("My Tools/Load All Sheets from Google Sheets (OAuth 2.0)")]
    public static void LoadAllSheets()
    {
        InitializeGoogleSheetsService();
        foreach (var sheetName in sheetNames)
        {
            EditorCoroutineUtility.StartCoroutineOwnerless(GetDataCoroutine(sheetName));
        }
    }

    private static void InitializeGoogleSheetsService()
    {
        string jsonPath = Path.Combine(Application.streamingAssetsPath, jsonKeyFileName);

        if (!File.Exists(jsonPath))
        {
            Debug.LogError($"Google Service JSON 파일을 찾을 수 없습니다: {jsonPath}");
            return;
        }

        GoogleCredential credential;
        using (var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(new string[] { SheetsService.Scope.SpreadsheetsReadonly });
        }

        sheetsService = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "My Unity Google Sheets API",
        });
    }

    private static IEnumerator GetDataCoroutine(string sheetName)
    {
        if (sheetsService == null)
        {
            Debug.LogError("Google Sheets API 서비스가 초기화되지 않았습니다.");
            yield break;
        }

        string range = $"{sheetName}!A1:Z"; // 가져올 범위
        SpreadsheetsResource.ValuesResource.GetRequest request = sheetsService.Spreadsheets.Values.Get(spreadsheetId, range);
        Task<ValueRange> responseTask = request.ExecuteAsync();
        yield return new WaitUntil(() => responseTask.IsCompleted);

        if (responseTask.Exception != null)
        {
            Debug.LogError("Error: " + responseTask.Exception.Message);
        }
        else
        {
            Debug.Log("✅ 데이터 가져오기 성공!");
        }
    }
}

 

 

🚀 Google Sheets API(OAuth 2.0)를 적용하여, 스프레드시트를 공개하지 않고 데이터를 가져올 수 있었습니다.
🚀 NuGet 패키지가 Unity에서 인식되지 않을 경우, 필요한 .dll을 직접 추가하는 방법도 필요하다는 점을 배웠습니다.
🚀 DLL을 수동으로 추가하고 Visual Studio에서 참조를 설정하면 오류 없이 Google Sheets API를 사용할 수 있습니다!

 

구글 시트 ID 등 기타 참고

아래 링크는 이전 구글스프레드시트 전체공개(공개해도 되는 데이터만) 방식으로 API키를 이용한 방법의 포스팅입니다.

https://ssscool.tistory.com/727

 

유니티 에디터 메뉴에 커스텀 버튼 만들기 및 구글 스프레드시트에서 데이터 불러와서 파일로

유니티 에디터 메뉴에 커스텀 버튼 만들기 및 구글 스프레드시트에서 데이터 불러와서 파일로 저장하기 Creating a custom button in the Unity Editor menu and loading data from Google Spreadsheet and saving it as a file 

ssscool.tistory.com

 

반응형