AWS 실습: DynamoDB를 Unity에서 사용
AWS 실습: DynamoDB를 Unity에서 사용
선행 포스트
AWS DynamoDB를 Unity에서 사용
- 콘솔에 Cognito를 입력해서 Cognito 서비스 입장.
- “AWS 서비스에 대한 액세스 권한 부여” 선택 후 “자격 증명 풀 생성” 클릭.
- 자격 증명 이름을 설정하고 새 자격 증명 풀을 만듦.
- 인증되지 않은 사용자가 접속하기 위한 것이므로 “인증되지 않은 자격 증명에 대한 액세스 활성화” 클릭
- 인증되지 않은 자격 증명에 대한 액세스를 허용.
- AWS 자격 증명 얻기 항목에 표시된 자격 증명 풀 ID를 기록해 두고, 대시보드로 이동.
- AWS SDK 다운로드는 현재(2022-11-13) 기준으로 잘못된 위치로 리다이렉션되므로 이용 금지.
- 자격 증명 풀 ID가 노출되지 않도록 주의.
- DynamoDB 테이블 생성. 테이블 이름과 파티션 키를 입력하고, 정렬 키를 입력하지 않도록 주의.
- 6번에서 생성된 테이블에 항목 생성으로 데이터 추가. 이 때 “새 속성 추가” - “숫자"를 클릭한 후 다음과 같이 score 속성값을 입력.
- DynamoDB에 값을 입력한 예시.
- 콘솔에 IAM을 입력해서 IAM 서비스 입장.
- “역할"을 클릭 후 3번에서 생성한 풀 이름 뒤에 Unauth가 붙은 역할을 선택.
- 신뢰 관계를 누른 후 검은색 부분이 5번에서 기록한 값과 동일한지 확인.
- 인증되지 않은 사용자를 위한 역할이므로, 빨간색 네모 부분이 “unauthenticated"인지도 역시 확인.
- 권한 항목으로 돌아가 권한 추가 - 정책 연결 클릭.
- 정책 생성 클릭.
- 다음과 같이 JSON에서 다음과 같이 입력하고 다음 클릭.
- 해당 내용은 DynamoDB에 CRUD 작업을 가능하게 해 주는 정책 내용임.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:DescribeTable",
"dynamodb:ListTables",
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:Scan",
"dynamodb:Query"
],
"Resource": "*"
}
]
}
- 태그를 추가하고 싶은 경우 추가한 후 다음을 클릭.
- 정책 이름과 설명을 입력하고 “정책 생성” 클릭.
- 생성된 정책을 클릭하고 “정책 연결"을 클릭.
이 링크를 통해 SDK를 다운받고 압축 해제.
다운받은 파일을 유니티 프로젝트에 넣음. 여기에서는 Assets 아래에 넣음.
- 다운받은 폴더 내부에 IdentityManagement와 DynamoDB를 각각 눌러서 실행.
- 각각 다음과 같은 창이 나오면 Import 버튼을 누름.
- 다음과 같은 게임 오브젝트를 만들고 스크립트를 생성.
- 스크립트에 다음과 같은 코드 삽입. 이 코드에 대한 설명은 마지막에 첨부.
using UnityEngine;
using Amazon;
using Amazon.CognitoIdentity;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
public class ProgramStart : MonoBehaviour
{
CognitoAWSCredentials credentials;
AmazonDynamoDBClient client;
DynamoDBContext context;
[DynamoDBTable("Score")]
public class ServerScore
{
[DynamoDBHashKey]
public string id { get; set; }
[DynamoDBProperty]
public int score { get; set; }
}
private void Awake()
{
UnityInitializer.AttachToGameObject(this.gameObject);
credentials = new CognitoAWSCredentials("ap-northeast-1:ae632f7a-de85-4dc6-8656-df89585d1c03", RegionEndpoint.APNortheast1);
client = new AmazonDynamoDBClient(credentials, RegionEndpoint.APNortheast1);
context = new DynamoDBContext(client);
context.LoadAsync<ServerScore>("player1", (AmazonDynamoDBResult<ServerScore> result) =>
{
if (result.Exception == null)
{
Debug.Log(result.Result.score);
}
else
{
Debug.Log(result.Exception);
}
});
ServerScore newServerScore = new ServerScore
{
id = "NewPlayer",
score = 19,
};
context.SaveAsync(newServerScore, (result) =>
{
if (result.Exception == null)
{
Debug.Log("Add an score");
}
else
{
Debug.Log(result.Exception);
}
});
}
}
- 코드를 수행할 경우 DB에 새로운 플레이어가 생기게 됨.
- 콘솔창에도 잘 등장하는 것을 확인.
코드 부연 설명
- Credentials, DBClient, DBContext를 저장하는 변수.
CognitoAWSCredentials credentials;
AmazonDynamoDBClient client;
DynamoDBContext context;
- 테이블 구조를 나타내는 클래스. 위에 반드시
[DynamoDBTable("연결할 테이블 이름")]
을 기입해야 한다.
[DynamoDBTable("Score")]
public class ServerScore
{
[DynamoDBHashKey]
public string id { get; set; }
[DynamoDBProperty]
public int score { get; set; }
}
- SDK를 사용하기 위해 초기화를 해 주고, 5번에서 사용한 풀 ID를 YOUR_POOL_ID 위치에 입력해서 DB client와 context를 획득.
UnityInitializer.AttachToGameObject(this.gameObject);
credentials = new CognitoAWSCredentials(YOUR_POOL_ID, RegionEndpoint.APNortheast1);
client = new AmazonDynamoDBClient(credentials, RegionEndpoint.APNortheast1);
context = new DynamoDBContext(client);
- LoadAsync함수를 통해 서버에서 id가 player 1인 row의 정보를 비동기식으로 받아오고, 받은 경우 해당 행의 score 속성을 출력.
context.LoadAsync<ServerScore>("player1", (AmazonDynamoDBResult<ServerScore> result) =>
{
if (result.Exception == null)
{
Debug.Log(result.Result.score);
}
else
{
Debug.Log(result.Exception);
}
});
- 새 유저 정보를 하나 만들고, 비동기식으로 DB에 저장.
ServerScore newServerScore = new ServerScore
{
id = "NewPlayer",
score = 19,
};
context.SaveAsync(newServerScore, (result) =>
{
if (result.Exception == null)
{
Debug.Log("Add an score");
}
else
{
Debug.Log(result.Exception);
}
});
References
- https://greenapple16.tistory.com/35
- https://greenapple16.tistory.com/36
- https://docs.aws.amazon.com/ko_kr/mobile/sdkforunity/developerguide/dynamodb.html