Last active
September 26, 2024 07:24
-
-
Save yoyu777/352f6279b83a19813345ce99293ff6dd to your computer and use it in GitHub Desktop.
sheetreader for Unity (Sheets API v4)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Google.Apis.Services; | |
using Google.Apis.Auth.OAuth2; | |
using Google.Apis.Sheets.v4; | |
using Google.Apis.Sheets.v4.Data; | |
using UnityEngine; | |
class SheetReader | |
{ | |
static private String spreadsheetId = "1vc2kKeLprOJynjUDglqf10ztD7bog"; | |
static private String serviceAccountID = "[email protected]"; | |
static private SheetsService service; | |
static SheetReader() | |
{ | |
// Loading private key from resources as a TextAsset | |
String key = Resources.Load<TextAsset>("Creds/key").ToString(); | |
Debug.Log(key); | |
// Creating a ServiceAccountCredential.Initializer | |
// ref: https://googleapis.dev/dotnet/Google.Apis.Auth/latest/api/Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer.html | |
ServiceAccountCredential.Initializer initializer=new ServiceAccountCredential.Initializer(serviceAccountID); | |
// Getting ServiceAccountCredential from the private key | |
// ref: https://googleapis.dev/dotnet/Google.Apis.Auth/latest/api/Google.Apis.Auth.OAuth2.ServiceAccountCredential.html | |
ServiceAccountCredential credential = new ServiceAccountCredential( | |
initializer.FromPrivateKey(key) | |
); | |
service = new SheetsService( | |
new BaseClientService.Initializer() | |
{ | |
HttpClientInitializer = credential, | |
} | |
); | |
} | |
public IList<IList<object>> getSheetRange(String sheetNameAndRange) | |
{ | |
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, sheetNameAndRange); | |
ValueRange response = request.Execute(); | |
IList<IList<object>> values = response.Values; | |
if (values != null && values.Count > 0) | |
{ | |
return values; | |
} | |
else | |
{ | |
Debug.Log("No data found."); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had the same problem, for anyone who has it as well I found the following solution:
I create the credential the following way and pass it to the SheetsService, and all other code remains unchanged.