애플리케이션 측 SDK 통합
- 로그인 시스템, 인게임 스토어 및 기타 페이지에서 사용할 인터페이스를 디자인합니다.
- SDK 메소드를 사용하여 사용자 인증, 스토어 디스플레이, 구매 등을 위한 애플리케이션 로직을 구현합니다.
<xsollaExtention>/assets/scripts/samples
디렉터리에서 확인할 수 있습니다.사용자 이름/이메일 및 암호를 통한 사용자 등록 및 로그인
SDK 메소드를 사용하여 구현하기 위한 지침:
사용자 이름 또는 이메일 주소로 사용자를 인증할 수 있습니다. 다음 예시에서 사용자를 사용자 이름 이름으로 인증합니다. 반면 이메일 주소는 등록 확인 및 암호 재설정에 사용합니다.
사용자 등록 구현
이 튜토리얼이 설명하는 논리의 구현:페이지 컨트롤러 생성
등록 페이지용 장면을 생성한 후 추가할 요소:
- 사용자 이름 필드
- 사용자 이메일 주소 필드
- 사용자 암호 필드
- 등록 버튼
페이지 구조 예시:

등록 스크립트 구성 요소 생성
- RegistrationComponent 생성을 클릭한 후 다음 속성을 추가합니다.
usernameEditBox
emailEditBox
passwordEditBox
signUpButton
- 선택 사항입니다. 코드를 사용하여 콜백 함수를 버튼에 바인딩할 때 사용합니다.
- 스크립트 예시와 같이
SignUpButton
을 클릭할 때 호출되는 메소드를RegistrationComponent
클래스에 추가하고, 클릭 이벤트를 처리하는 로직을 추가합니다. - 장면의 노드에 RegistrationComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 장면 요소를
RegistrationComponent
의 속성에 바인딩합니다.

- 다음 방법 중 하나를 사용하여 등록 버튼에 콜백을 바인딩합니다.
- 아래 그림과 같이
Inspector 패널 사용 - 페이지 스크립트에 아래의 코드 블록 삽입
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.signUpButton.node.on(Button.EventType.CLICK, this.onSignUpClicked, this);
}
스크립트 예시에서 onComplete
및 onError
메소드는 표준 console.log
메소드를 호출합니다. 오류가 발생하면 오류 코드 및 설명이 error
매개변수에서 전달됩니다.
등록이 성공적이라면 등록 이메일 또는 로그인 페이지 열기 요청 재전송을 포함하는 페이지 열기 같은 다른 동작을 추가할 수 있습니다.
- typescript
import { _decorator, Button, Component, EditBox } from 'cc';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
const { ccclass, property } = _decorator;
@ccclass('RegistrationComponent')
export class RegistrationComponent extends Component {
@property(EditBox)
usernameEditBox: EditBox;
@property(EditBox)
emailEditBox: EditBox;
@property(EditBox)
passwordEditBox: EditBox;
@property(Button)
signUpButton: Button;
start() {
this.signUpButton.node.on(Button.EventType.CLICK, this.onSignUpClicked, this);
}
onSignUpClicked() {
XsollaAuth.registerNewUser(this.usernameEditBox.string, this.passwordEditBox.string, this.emailEditBox.string, 'xsollatest', null, null, token => {
if(token != null) {
console.log(`Successful login. Token - ${token.access_token}`);
}
else {
console.log('Thank you! We have sent you a confirmation email');
}
}, err => {
console.log(err);
});
}
}
등록 확인 이메일 설정
성공적인 등록 후 사용자는 지정된 주소로 등록 확인 이메일을 받습니다. 관리자 페이지에서 사용자에게 보낼 이메일을 맞춤 설정할 수 있습니다.
모바일 애플리케이션을 개발 중이라면 사용자가 등록 확인을 한 후에 애플리케이션으로 사용자들 돌려보내기 위한 딥 링크를 설정합니다.
등록 확인 이메일 재전송 요청 구현
이 튜토리얼이 설명하는 논리의 구현:페이지 컨트롤러 생성
확인 이메일 재전송 요청 페이지용 장면을 생성한 후 추가해야 하는 요소:
- 사용자 이름/이메일 필드
- 이메일 재전송 버튼
페이지 구조 예시:

이메일 재전송 스크립트 구성 요소 생성
- ResendConfirmationEmailComponent 생성을 수행한 후 다음 속성을 추가합니다.
usernameTextBox
resendEmailButton
- 선택 사항입니다. 코드를 사용하여 콜백 함수를 버튼에 바인딩할 때 사용합니다.
- 스크립트 예시와 같이
ResendEmail
을 클릭할 때 호출되는 메소드를ResendConfirmationEmailComponent
클래스에 추가하고, 클릭 이벤트를 처리하는 로직을 추가합니다. - 장면의 노드에 ResendConfirmationEmailComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 장면 요소를
ResendConfirmationEmailComponent
의 속성에 바인딩합니다.

- 등록 확인 이메일 요청 버튼에 콜백 바인딩하는 방법:
- 아래 그림과 같이
Inspector 패널을 사용합니다. - 확인 이메일 재전송 요청이 있는 페이지의 스크립트에 아래의 코드 블록을 삽입합니다.
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.resendEmailButton.node.on(Button.EventType.CLICK, this.onResendEmailClicked, this);
}
요청이 성공적이면 사용자가 등록 확인 이메일을 등록할 동안 지정한 이메일 주소로 받습니다.
스크립트 예시에서 onComplete
및 onError
메소드가 표준 console.log
메소드를 호출합니다. 다른 동작을 추가할 수 있습니다.
오류가 발생하면 오류 코드와 설명이 error
매개변수에서 전달됩니다.
- typescript
import { _decorator, Button, Component, EditBox } from 'cc';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
const { ccclass, property } = _decorator;
@ccclass('ResendConfirmationEmailComponent')
export class ResendConfirmationEmailComponent extends Component {
@property(EditBox)
usernameEditBox: EditBox;
@property(Button)
resendEmailButton: Button;
start() {
this.resendEmailButton.node.on(Button.EventType.CLICK, this.onResendEmailClicked, this);
}
onResendEmailClicked() {
XsollaAuth.resendAccountConfirmationEmail(this.usernameEditBox.string, 'xsollatest', null, () => {
console.log('A verification link has been successfully sent to your email');
}, err => {
console.log(err);
});
}
}
사용자 로그인 구현
이 튜토리얼이 설명하는 논리의 구현:페이지 컨트롤러 생성
로그인 페이지용 장면을 생성하고 다음 요소 추가:
- 사용자 이름 필드
- 암호 필드
- 기억 토글
- 로그인 버튼
페이지 구조 예시:

로그인 스크립트 구성 요소 생성
- LoginComponent 생성을 클릭한 후 다음 속성을 추가합니다.
usernameEditBox
passwordEditBox
remeberMeToggle
loginButton
- 선택 사항입니다. 코드를 사용하여 콜백 함수를 버튼에 바인딩할 때 사용합니다.
- 스크립트 예시와 같이
LoginButton
을 클릭할 때 호출되는 메소드를LoginComponent
클래스에 추가하고, 클릭 이벤트를 처리하는 로직을 추가합니다. - 장면의 노드에 LoginComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 장면 요소를
LoginComponent
의 속성에 바인딩합니다.

- 다음 방법 중 하나를 사용하여 로그인 버튼에 콜백을 바인딩합니다.
- 아래 그림과 같이
Inspector 패널 사용 - 페이지 스크립트에 아래의 코드 블록 삽입
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.loginButton.node.on(Button.EventType.CLICK, this.onLoginClicked, this);
}
스크립트 예시에서 onComplete
및 onError
메소드가 표준 console.log
메소드를 호출합니다. 다른 동작을 추가할 수 있습니다.
오류가 발생하면 오류 코드와 설명이 error
매개변수에서 전달됩니다.
- typescript
import { _decorator, Button, Component, EditBox, Toggle } from 'cc';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
const { ccclass, property } = _decorator;
@ccclass('LoginComponent')
export class LoginComponent extends Component {
@property(EditBox)
usernameEditBox: EditBox;
@property(EditBox)
passwordEditBox: EditBox;
@property(Toggle)
remeberMeToggle: Toggle;
@property(Button)
loginButton: Button;
start() {
this.loginButton.node.on(Button.EventType.CLICK, this.onLoginClicked, this);
}
onLoginClicked() {
XsollaAuth.authByUsernameAndPassword(this.usernameEditBox.string, this.passwordEditBox.string, this.remeberMeToggle.isChecked, token => {
console.log('Successful login. Token - ${token.access_token}');
}, err => {
console.log(err);
});
}
}
암호 재설정 구현
이 튜토리얼이 설명하는 논리의 구현:페이지 컨트롤러 생성
암호 재설정 페이지에 대한 장면을 만든 후 추가해야 하는 항목:
- 사용자 이름 필드
- 암호 재설정 버튼
페이지 구조 예시:

암호 재설정 스크립트 구성 요소 생성
- ResetPasswordComponent 생성을 수행한 후 다음 속성을 추가합니다.
usernameEditBox
resetPasswordButton
- 선택 사항입니다. 코드를 사용하여 콜백 함수를 버튼에 바인딩할 때 사용합니다.
- 스크립트 예시와 같이
ResetPassword
을 클릭할 때 호출되는 메소드를ResetPasswordComponent
클래스에 추가하고, 클릭 이벤트를 처리하는 로직을 추가합니다. - 장면의 노드에 ResetPasswordComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 장면 요소를
ResetPasswordComponent
의 속성에 바인딩합니다.

- 다음 방법 중 하나를 사용하여 암호 재설정 버튼에 콜백을 바인딩합니다.
- 아래 그림과 같이
Inspector 패널 사용 - 페이지 스크립트에 아래의 코드 블록 삽입
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.resetPasswordButton.node.on(Button.EventType.CLICK, this.onResetPasswordClicked, this);
}
스크립트 예시에서 onComplete
및 onError
메소드가 표준 console.log
메소드를 호출합니다. 다른 동작을 추가할 수 있습니다.
오류가 발생하면 오류 코드와 설명이 error
매개변수에서 전달됩니다.
- typescript
import { _decorator, Button, Component, EditBox } from 'cc';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
const { ccclass, property } = _decorator;
@ccclass('ResetPasswordComponent')
export class ResetPasswordComponent extends Component {
@property(EditBox)
usernameEditBox: EditBox;
@property(Button)
resetPasswordButton: Button;
start() {
this.resetPasswordButton.node.on(Button.EventType.CLICK, this.onResetPasswordClicked, this);
}
onResetPasswordClicked() {
XsollaAuth.resetPassword(this.usernameEditBox.string, null, () => {
console.log('Follow the instructions we sent to your email');
}, err => {
console.log(err);
});
}
}
소셜 로그인
본 지침은 SDK 메소드를 통하여 사용자의 SNS 계정으로 사용자 등록 및 로그인을 구현하는 방법을 보여줍니다.
사용자 이름/사용자 이메일 주소 및 비밀번호를 통한 사용자 인증과는 달리, 사용자 등록을 위한 별도의 로직을 구현할 필요가 없습니다. 사용자가 SNS를 통해 최초 로그인 하는 경우, 새 계정이 자동으로 생성됩니다.
여러분의 애플리케이션에서 대체 인증 메소드를 자체 구현한 경우, 다음 조건이 일치하면 해당 SNS 계정이 기존 사용자 계정에 자동으로 연결 됩니다.
- 사용자 이름/이메일 주소 및 비밀번호로 가입한 사용자가 SNS 계정을 통해 애플리케이션에 로그인했습니다.
- SNS는 이메일 주소를 반환합니다.
- SNS의 사용자 이메일 주소가 애플리케이션에서 가입 시 사용한 이메일 주소와 동일합니다.
이 튜토리얼이 설명하는 논리의 구현:
Facebook 계정을 통해 사용자 로그인을 설정하는 방법을 보여주는 예시입니다. 모든 소셜 네트워크를 같은 압법으로 설정할 수 있습니다.
이 예시는 기본적인 SDK 메소드에 대해 소개합니다. 애플리케이션은 일반적으로 더 복잡한 인터페이스와 논리를 필요로 합니다.
페이지 컨트롤러 생성
소셜 로그인 페이지용 장면을 생성하고 소셜 로그인 버튼을 이에 추가합니다.
페이지 구조 예시:

소셜 로그인 스크립트 구성 요소 생성
- SocialLoginComponent 생성. 코드를 사용하여 소셜 로그인 버튼에 콜백 함수를 바인딩하려면
socialLoginButton
속성을 추가합니다. SocialLogin
클릭 시 호출되는 메소드를SocialLoginComponent
클래스에 추가하고, 스크립트 예시와 같이 클릭 이벤트를 처리하는 로직을 추가합니다.
- 장면의 노드에 SocialLoginComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이
SocialLoginComponent
의socialLoginButton
속성에SocialLogin
버튼을 바인딩합니다.

- 다음 방법 중 하나를 사용하여 로그인 버튼에 콜백을 바인딩합니다.
- 아래 그림과 같이
Inspector 패널 사용 - 페이지 스크립트에 아래의 코드 블록 삽입
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.socialLoginButton.node.on(Button.EventType.CLICK, this.onSocialLoginClicked, this);
}
스크립트 예시에서 onComplete
, onCanceled
및 onError
메소드는 표준 console.log
메소드를 호출합니다. 오류가 발생하면 오류 코드 및 설명이 error
매개 변수에서 전달됩니다.
등록이 성공적이라면 등록 이메일 또는 로그인 페이지 열기 요청 재전송을 포함하는 페이지 열기 같은 다른 동작을 추가할 수 있습니다.
- typescript
import { _decorator, Button, Component } from 'cc';
import { Token, XsollaAuth } from '../../api/XsollaAuth';
const { ccclass, property } = _decorator;
namespace authorization {
@ccclass('SocialLoginComponent')
export class SocialLoginComponent extends Component {
@property(Button)
socialLoginButton: Button;
start() {
this.socialLoginButton.node.on(Button.EventType.CLICK, this.onSocialLoginClicked, this);
}
onSocialLoginClicked() {
XsollaAuth.authSocial('facebook', (token: Token) => {
console.log(`Successful social authentication. Token - ${token.access_token}`);
}, () => {
console.log('Social auth was canceled');
}, (error:string) => {
console.log(error);
});
}
}
}
아이템 카탈로그 표시
이 튜토리얼은 SDK 메소드를 사용하여 인게임 스토어에서 다음 아이템을 표시하는 방법을 보여줍니다.
- 가상 아이템
- 번들
- 인게임 재화 패키지
시작하기 전에 관리자 페이지의 아이템을 구성해야 합니다.
이 튜토리얼이 설명하는 논리의 구현:
카탈로그의 모든 아이템 예시가 표시하는 내용:
- 이름
- 설명
- 가격
- 이미지
이 정보가 인게임 스토어에 정보가 저장되어 있다면 아이템에 관한 다른 정보도 표시할 수 있습니다.
가상 아이템 표시 구현
아이템 위젯 생성
- 프리패브를 생성합니다. 이렇게 하려면 폴더의 컨텍스트 메뉴에서
Create > Node Prefab 를 선택합니다. - 생성된 프리패브를 엽니다.
- 아래 이미지와 같이 프리패브의 루트에
UITransform
구성 요소를 추가하고 콘텐츠 크기를 설정합니다.

- 다음 UI 요소를 프리패브 하위 개체로 추가하고 해당하는 비주얼을 구성합니다.
- 위젯 배경 이미지
- 아이템 이름
- 아이템 설명
- 아이템 가격
- 아이템 이미지
위젯 구조 예시:

아이템 위젯 스크립트 생성
StoreItemComponent
생성을 수행한 후 다음 속성을 추가합니다.iconSprite
itemNameLabel
itemDescriptionLabel
priceLabel
- 스크립트 예시와 같이
init
메소드와 초기화 논리를StoreItemComponent
클래스에 추가합니다. - StoreItemComponent를 프리패브의 루트 노드에 연결합니다.
- 그림과 같이 프리패브 요소를
StoreItemComponent
의 속성에 바인딩합니다.

위젯 스크립트 예시(StoreItemComponent):
- typescript
import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { StoreItem } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
const { ccclass, property } = _decorator;
@ccclass('StoreItemComponent')
export class StoreItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
itemNameLabel: Label;
@property(Label)
itemDescriptionLabel: Label;
@property(Label)
priceLabel: Label;
private _data: StoreItem;
init(data: StoreItem) {
this._data = data;
this.itemNameLabel.string = data.name;
this.itemDescriptionLabel.string = data.description;
if (data.virtual_prices.length > 0) {
this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
} else {
this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
}
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Can’t load image with URL ${data.image_url}`);
}
});
}
}
페이지 컨트롤러 생성
아이템 카탈로그 페이지에 대한 장면을 생성하고 ScrollView
요소를 추가합니다.
페이지 구조 예시:

생성된 StoreItem
프리패브와 일치하는 ScrollView
를 만들기 위해 크기를 설정하는 방법:
ScrollView
노드와 내부view
노드에서ContentSize
매개 변수 값을 변경합니다.Layout
구성 요소를content
노드에 바인딩하고 이를 설정합니다. 예시에서는 다음과 같은 설정이 선택되어 있습니다.Type == vertical
ResizeMode == Container
아이템 카탈로그 스크립트 구성 요소 생성
- ItemsCatalogComponent 생성 작업을 수행한 후 다음 속성을 추가합니다.
itemsScrollView
storeItemPrefab
- 스크립트 예시와 같이
start 수명 주기 함수와 초기화 논리를ItemsCatalogComponent
클래스에 추가합니다. - 장면의 노드에 ItemsCatalogComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 프리패브 요소를
ItemsCatalogComponent
의 속성에 바인딩합니다.

클래스 스크립트 예시(ItemsCatalogComponent):
- typescript
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
import { StoreItemComponent } from './StoreItemComponent';
const { ccclass, property } = _decorator;
@ccclass('ItemsCatalogComponent')
export class ItemsCatalogComponent extends Component {
@property(ScrollView)
itemsScrollView: ScrollView;
@property(Prefab)
storeItemPrefab: Prefab;
start() {
XsollaCatalog.getCatalog(null, null, [], itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let storeItem = instantiate(this.storeItemPrefab);
this.itemsScrollView.content.addChild(storeItem);
storeItem.getComponent(StoreItemComponent).init(itemsData.items[i]);
}
});
}
}
스크립트 작업 결과 예시:

번들 표시 구현
번들 위젯 생성
- 프리패브를 생성합니다. 이렇게 하려면 폴더의 컨텍스트 메뉴에서
Create > Node Prefab 를 선택합니다. - 생성된 프리패브를 엽니다.
- 아래 이미지와 같이 프리패브의 루트에
UITransform
구성 요소를 추가하고 콘텐츠 크기를 설정합니다.

- 다음 UI 요소를 프리패브 하위 개체로 추가하고 해당하는 비주얼을 구성합니다.
- 위젯 배경 이미지
- 번들 이름
- 번들 설명
- 번들 가격
- 번들 이미지
- 번들 콘텐츠 설명(아이템 및 해당 수량)
위젯 구조 예시:

번들 위젯 스크립트 생성
- BundleItemComponent 생성을 수행한 후 다음 속성을 추가합니다.
iconSprite
bundleNameLabel
bundleDescriptionLabel
priceLabel
contentDescriptionlabel
- 스크립트 예시와 같이
init
메소드와 초기화 논리를BundleItemComponent
클래스에 추가합니다. - BundleItemComponent를 프리패브의 루트 노드에 연결합니다.
- 그림과 같이 프리패브 요소를
BundleItemComponent
의 속성에 바인딩합니다.

위젯 스크립트 예시(BundleItemComponent):
- typescript
import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { StoreBundle } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
const { ccclass, property } = _decorator;
@ccclass('BundleItemComponent')
export class BundleItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
bundleNameLabel: Label;
@property(Label)
bundleDescriptionLabel: Label;
@property(Label)
priceLabel: Label;
@property(Label)
contentDescriptionLabel: Label;
init(data: StoreBundle) {
this.bundleNameLabel.string = data.name;
this.bundleDescriptionLabel.string = data.description;
if (data.virtual_prices.length > 0) {
this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
} else {
this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
}
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Can’t load image with URL ${data.image_url}`);
}
});
this.contentDescriptionLabel.string = 'This bundle includes '+ data.content.length + ' items: ';
var bandles = data.content.map(bundle => bundle.name).join(', ');
this.contentDescriptionLabel.string += bandles;
}
}
페이지 컨트롤러 생성
번들 카탈로그 페이지에 대한 장면을 생성하고 ScrollView
요소를 추가합니다.
페이지 구조 예시:

생성된 BundleItem
프리패브와 일치하는 ScrollView
를 만들기 위해 크기를 설정하는 방법:
ScrollView
노드와 내부view
노드에서ContentSize
매개 변수 값을 변경합니다.Layout
구성 요소를content
노드에 바인딩하고 이를 설정합니다. 예시에서는 다음과 같은 설정이 선택되어 있습니다.Type == vertical
ResizeMode == Container
번들 카탈로그 스크립트 구성 요소 생성
- BundlesCatalogComponent를 생성하고 다음 속성을 추가합니다.
itemsScrollView
bundleItemPrefab
- 스크립트 예시와 같이
start 수명 주기 함수와 초기화 논리를BundlesCatalogComponent
클래스에 추가합니다. - 장면의 노드에 BundlesCatalogComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 프리패브 요소를
BundlesCatalogComponent
의 속성에 바인딩합니다.

클래스 스크립트 예시(BundlesCatalogComponent):
- typescript
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
import { BundleItemComponent } from './BundleItemComponent';
const { ccclass, property } = _decorator;
@ccclass('BundlesCatalogComponent')
export class BundlesCatalogComponent extends Component {
@property(ScrollView)
itemsScrollView: ScrollView;
@property(Prefab)
bundleItemPrefab: Prefab;
start() {
XsollaCatalog.getBundleList(null, null, [], itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let bundleItem = instantiate(this.bundleItemPrefab);
this.itemsScrollView.content.addChild(bundleItem);
bundleItem.getComponent(BundleItemComponent).init(itemsData.items[i]);
}
});
}
}
스크립트 작업 결과 예시:

인게임 재화 패키지 카탈로그 표시 구현
인게임 재화 패키지용 위젯 생성
- 프리패브를 생성합니다. 이렇게 하려면 폴더의 컨텍스트 메뉴에서
Create > Node Prefab 를 선택합니다. - 생성된 프리패브를 엽니다.
- 아래 이미지와 같이 프리패브의 루트에
UITransform
구성 요소를 추가하고 콘텐츠 크기를 설정합니다.

- 다음 UI 요소를 프리패브 하위 개체로 추가하고 해당하는 비주얼을 구성합니다.
- 위젯 배경 이미지
- 인게임 재화 이름
- 인게임 재화 설명
- 인게임 재화 가격
- 인게임 재화 이미지
위젯 구조 예시:

인게임 재화 패키지용 위젯 스크립트 생성
- CurrencyPackageItemComponent 생성을 수행한 후 다음 속성을 추가합니다.
iconSprite
currencyNameLabel
currencyDescriptionLabel
priceLabel
- 스크립트 예시와 같이
init
메소드와 초기화 논리를CurrencyPackageItemComponent
클래스에 추가합니다. - CurrencyPackageItemComponent를 프리패브의 루트 노드에 연결합니다.
- 그림과 같이 프리패브 요소를
CurrencyPackageItemComponent
의 속성에 바인딩합니다.

위젯 스크립트 예시(CurrencyPackageItemComponent):
- typescript
import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { VirtualCurrencyPackage } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
const { ccclass, property } = _decorator;
@ccclass('CurrencyPackageItemComponent')
export class CurrencyPackageItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
currencyNameLabel: Label;
@property(Label)
currencyDescriptionLabel: Label;
@property(Label)
priceLabel: Label;
init(data: VirtualCurrencyPackage) {
this.currencyNameLabel.string = data.name;
this.currencyDescriptionLabel.string = data.description;
if (data.virtual_prices.length > 0) {
this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
} else {
this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
}
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Can’t load image with URL ${data.image_url}`);
}
});
}
}
페이지 컨트롤러 생성
인게임 재화 패키지 카탈로그 페이지에 대한 장면을 생성하고 ScrollView
요소를 추가합니다.
페이지 구조 예시:

생성된 CurrencyPackageItem
프리패브와 일치하는 ScrollView
를 만들기 위해 크기를 설정하는 방법:
ScrollView
노드와 내부view
노드에서ContentSize
매개 변수 값을 변경합니다.Layout
구성 요소를content
노드에 바인딩하고 이를 설정합니다. 예시에서는 다음과 같은 설정이 선택되어 있습니다.Type == vertical
ResizeMode == Container
통화 패키지 카탈로그 스크립트 구성 요소 생성
CurrencyPackagesCatalogComponent
를 생성하고 다음 속성을 추가합니다.itemsScrollView
currencyPackageItemPrefab
- 스크립트 예시와 같이
start 수명 주기 함수와 초기화 논리를CurrencyPackagesCatalogComponent
클래스에 추가합니다. - 장면의 노드에 CurrencyPackagesCatalogComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 프리패브 요소를
CurrencyPackagesCatalogComponent
의 속성에 바인딩합니다.

클래스 스크립트 예시(CurrencyPackagesCatalogComponent):
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
import { CurrencyPackageItemComponent } from './CurrencyPackageItemComponent';
const { ccclass, property } = _decorator;
@ccclass('CurrencyPackagesCatalogComponent')
export class CurrencyPackagesCatalogComponent extends Component {
@property(ScrollView)
itemsScrollView: ScrollView;
@property(Prefab)
currencyPackageItemPrefab: Prefab;
start() {
XsollaCatalog.getVirtualCurrencyPackages(null, null, [], itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let currencyPackageItem = instantiate(this.currencyPackageItemPrefab);
this.itemsScrollView.content.addChild(currencyPackageItem);
currencyPackageItem.getComponent(CurrencyPackageItemComponent).init(itemsData.items[i]);
}
});
}
}
스크립트 작업 결과 예시:

실질 화폐용 가상 아이템 판매
이 섹션에서는 가상 아이템을 사용하여 실제 화폐로 아이템 판매하기를 구현할 수 있도록 SDK 메소드를 사용하는 방식을 설명합니다.
시작하기 전에 카탈로그에서 가상 아이템 표시 구현 작업을 수행합니다. 다음 예에서는 가상 아이템 구매 구현 방법을 설명합니다. 다른 아이템 유형용 구성은 이와 유사합니다.
이 튜토리얼이 설명하는 논리의 구현:
로그인 스크립트 예시에서 저희는 데모 계정 자격 증명을 사용합니다(사용자 이름 : xsolla
, 암호: xsolla
). 이 데모 계정은 데모 프로젝트에만 사용할 수 있습니다.
스크립트 샘플에는 카탈로그에 있는 아이템의 페이지별 표시 구현(페이지 매김)이 포함되어 있지 않습니다. 페이지 매김을 구현하려면 getCatalog
SDK 메소드의 offset
및 limit
매개 변수를 사용합니다. 한 페이지 당 최대 아이템 개수는 50개입니다. 카탈로그에 아이템이 50개 이상 있는 경우 페이지 매김이 필요합니다.
전체 아이템 위젯
아이템 위젯에 구매 버튼을 추가하고 이 버튼의 시각적 정보를 구성합니다.RC_StoreItemComponent
로 변경됩니다.
아이템 위젯 스크립트 완료
- 코드를 사용하여 콜백 함수를 구매 버튼에 바인딩하려면
RC_StoreItemComponent
에buyButton
속성을 추가합니다. - 스크립트 예시와 같이
BuyButton
클릭 시 호출되는 메소드를RC_StoreItemComponent
클래스에 추가하고 클릭 이벤트를 처리하는 논리를 추가합니다. - 다음 방식 중 하나를 사용하여 구매 버튼에 콜백 바인딩 작업을 수행합니다.
- 아래 그림과 같이
Inspector 패널 사용 - 페이지 스크립트에 아래 코드 블록 삽입
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
}
위젯 스크립트 예시(RC_StoreItemComponent):
- typescript
import { _decorator, assetManager, Button, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { StoreItem, XsollaCatalog } from '../../api/XsollaCatalog';
import { TokenStorage } from '../../common/TokenStorage';
import { OrderTracker } from '../../common/OrderTracker';
import { XsollaPayments } from '../../api/XsollaPayments';
const { ccclass, property } = _decorator;
export namespace sellForRealMoneyItem {
@ccclass('RC_StoreItemComponent')
export class RC_StoreItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
itemNameLabel: Label;
@property(Label)
itemDescriptionLabel: Label;
@property(Label)
priceLabel: Label;
@property(Button)
buyButton: Button;
private _data: StoreItem;
start() {
this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
}
init(data: StoreItem) {
this._data = data;
this.itemNameLabel.string = data.name;
this.itemDescriptionLabel.string = data.description;
if (data.virtual_prices.length > 0) {
this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
} else {
this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
}
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Cant load image with url ${data.image_url}`);
}
});
}
onBuyClicked() {
XsollaCatalog.fetchPaymentToken(TokenStorage.getToken().access_token, this._data.sku, 1, undefined, undefined, undefined, undefined, undefined, result => {
OrderTracker.checkPendingOrder(result.token, result.orderId, () => {
console.log('success purchase!');
}, error => {
console.log(`Order checking failed - Status code: ${error.status}, Error code: ${error.code}, Error message: ${error.description}`);
});
XsollaPayments.openPurchaseUI(result.token);
}, error => {
console.log(error.description);
});
}
}
}
전체 아이템 카탈로그 스크립트 구성 요소
RC_ItemsCatalogComponent
로 변경됩니다.스크립트 예시에 표시된 것처럼 RC_ItemsCatalogComponent
클래스의 start
메소드로 유효한 인증 토큰을 가져오기 위한 논리를 추가합니다.
클래스 스크립트 예시(RC_ItemsCatalogComponent):
- typescript
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
import { RC_StoreItemComponent } from './RC_StoreItemComponent';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
const { ccclass, property } = _decorator;
@ccclass('RC_ItemsCatalogComponent')
export class RC_ItemsCatalogComponent extends Component {
@property(ScrollView)
itemsScrollView: ScrollView;
@property(Prefab)
storeItemPrefab: Prefab;
start() {
XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
TokenStorage.saveToken(token, false);
XsollaCatalog.getCatalog(null, null, [], itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let storeItem = instantiate(this.storeItemPrefab);
this.itemsScrollView.content.addChild(storeItem);
storeItem.getComponent(RC_StoreItemComponent).init(itemsData.items[i]);
}
});
});
}
}
스크립트 작업 결과 예시:

인게임 재화용 가상 아이템 판매
이 섹션에서는 가상 아이템을 사용하여 인게임 재화로 아이템 판매하기를 구현할 수 있도록 SDK 메소드를 사용하는 방식을 설명합니다.
시작하기 전에 카탈로그의 가상 아이템 표시를 구현합니다. 다음 예에서는 가상 아이템 구매 구현 방법을 설명합니다. 다른 아이템 유형용 구성은 이와 유사합니다.
이 튜토리얼이 설명하는 논리의 구현:
로그인 스크립트 예시에서 저희는 데모 계정 자격 증명을 사용합니다(사용자 이름 : xsolla
, 암호: xsolla
). 이 데모 계정은 데모 프로젝트에만 사용할 수 있습니다.
스크립트 샘플에는 카탈로그에 있는 아이템의 페이지별 표시 구현(페이지 매김)이 포함되어 있지 않습니다. 페이지 매김을 구현하려면 getCatalog
SDK 메소드의 offset
및 limit
매개 변수를 사용합니다. 한 페이지 당 최대 아이템 개수는 50개입니다. 카탈로그에 아이템이 50개 이상 있는 경우 페이지 매김이 필요합니다.
아이템 위젯 완료
아이템 위젯에 구매 버튼을 추가하고 이 버튼의 시각적 정보를 구성합니다.VC_StoreItemComponent
로 변경됩니다.
아이템 위젯 스크립트 완료
- 코드를 사용하여 콜백 함수를 구매 버튼에 바인딩하려면
VC_StoreItemComponent
에buyButton
속성을 추가합니다. - 스크립트 예시와 같이
BuyButton
클릭 시 호출되는 메소드를VC_StoreItemComponent
클래스에 추가하고 클릭 이벤트를 처리하는 논리를 추가합니다. - 다음 방식 중 하나를 사용하여 구매 버튼에 콜백 바인딩 작업을 수행합니다.
- 아래 그림과 같이
Inspector 패널 사용 - 페이지 스크립트에 아래 코드 블록 삽입
- 아래 그림과 같이

코드를 통한 바인딩 콜백:
- typescript
start() {
this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
}
위젯 스크립트 예시(VC_StoreItemComponent):
- typescript
import { _decorator, assetManager, Button, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { StoreItem, XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
import { OrderTracker } from 'db://xsolla-commerce-sdk/scripts/common/OrderTracker';
const { ccclass, property } = _decorator;
@ccclass('VC_StoreItemComponent')
export class VC_StoreItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
itemNameLabel: Label;
@property(Label)
itemDescriptionLabel: Label;
@property(Label)
priceLabel: Label;
@property(Button)
buyButton: Button;
private _data: StoreItem;
start() {
this.buyButton.node.on(Button.EventType.CLICK, this.onBuyClicked, this);
}
init(data: StoreItem) {
this._data = data;
this.itemNameLabel.string = data.name;
this.itemDescriptionLabel.string = data.description;
if (data.virtual_prices.length > 0) {
this.priceLabel.string = data.virtual_prices[0].amount.toString() + ' ' + data.virtual_prices[0].name;
} else {
this.priceLabel.string = parseFloat(data.price.amount) + ' ' + data.price.currency;
}
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Can’t load image with URL ${data.image_url}`);
}
});
}
onBuyClicked() {
XsollaCatalog.purchaseItemForVirtualCurrency(TokenStorage.getToken().access_token, this._data.sku, this._data.virtual_prices[0].sku, orderId => {
OrderTracker.checkPendingOrder(TokenStorage.getToken().access_token, orderId, () => {
console.log('success purchase!');
}, error => {
console.log(`Order checking failed - Status code: ${error.status}, Error code: ${error.code}, Error message: ${error.description}`);
});
}, error => {
console.log(error.description);
});
}
}
전체 아이템 카탈로그 스크립트 구성 요소
VC_ItemsCatalogComponent
로 변경됩니다.스크립트 예시에 표시된 것처럼 VC_ItemsCatalogComponent
클래스의 start
메소드로 유효한 인증 토큰을 가져오기 위한 논리를 추가합니다.
클래스 스크립트 예시(VC_ItemsCatalogComponent):
- typescript
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaCatalog } from 'db://xsolla-commerce-sdk/scripts/api/XsollaCatalog';
import { VC_StoreItemComponent } from './VC_StoreItemComponent';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
import { TokenStorage } from 'db://xsolla-commerce-sdk/scripts/common/TokenStorage';
const { ccclass, property } = _decorator;
@ccclass('VC_ItemsCatalogComponent')
export class VC_ItemsCatalogComponent extends Component {
@property(ScrollView)
itemsScrollView: ScrollView;
@property(Prefab)
storeItemPrefab: Prefab;
start() {
XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
TokenStorage.saveToken(token, false);
XsollaCatalog.getCatalog(null, null, [], itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let storeItem = instantiate(this.storeItemPrefab);
this.itemsScrollView.content.addChild(storeItem);
storeItem.getComponent(VC_StoreItemComponent).init(itemsData.items[i]);
}
});
});
}
}
스크립트 작업 결과 예시:

인게임 재화 잔액 표시
이 튜토리얼은 메소드를 사용하여 귀하의 앱에서 인게임 재화 잔액을 표시하는 방법을 보여줍니다 .
잔액 표시용 위젯 생성
- 프리패브를 생성합니다. 이렇게 하려면 폴더의 컨텍스트 메뉴에서
Create > Node Prefab 를 선택합니다. - 생성된 프리패브를 엽니다.
- 아래 이미지와 같이 프리패브의 루트에
UITransform
구성 요소를 추가하고 콘텐츠 크기를 설정합니다.

- 다음 UI 요소를 프리패브 하위 개체로 추가하고 해당하는 비주얼을 구성합니다.
- 위젯 배경 이미지
- 인게임 재화 이름
- 인게임 재화 수량
- 인게임 재화 이미지
위젯 구조 예시:

잔액 표시 위젯 스크립트 생성
- CurrencyBalanceItemComponent 생성을 수행한 후 다음 속성을 추가합니다.
iconSprite
currencyNameLabel
quantityLabel
- 스크립트 예시와 같이
init
메소드와 초기화 논리를CurrencyBalanceItemComponent
클래스에 추가합니다. - CurrencyBalanceItemComponent를 프리패브의 루트 노드에 연결합니다.
- 그림과 같이 프리패브 요소를
CurrencyBalanceItemComponent
의 속성에 바인딩합니다.

위젯 스크립트 예시(CurrencyBalanceItemComponent):
- typescript
import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { VirtualCurrencyBalance } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
const { ccclass, property } = _decorator;
@ccclass('CurrencyBalanceItemComponent')
export class CurrencyBalanceItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
currencyNameLabel: Label;
@property(Label)
quantityLabel: Label;
init(data: VirtualCurrencyBalance) {
this.currencyNameLabel.string = data.name;
this.quantityLabel.string = data.amount.toString();
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Can’t load image with URL ${data.image_url}`);
}
});
}
}
페이지 컨트롤러 생성
인게임 재화 잔액 페이지에 대한 장면을 생성하고 ScrollView
요소를 추가합니다.
페이지 구조 예시:

생성된 CurrencyBalanceItem
프리패브와 일치하는 ScrollView
를 만들기 위해 크기를 설정하는 방법:
ScrollView
노드와 내부view
노드에서ContentSize
매개 변수 값을 변경합니다.Layout
구성 요소를content
노드에 바인딩하고 이를 설정합니다. 예시에서는 다음과 같은 설정이 선택되어 있습니다.Type == vertical
ResizeMode == Container
인게임 재화 잔액 스크립트 구성 요소 생성
- CurrencyBalanceComponent 생성 작업을 수행한 후 다음 속성을 추가합니다.
itemsScrollView
currencyBalanceItemPrefab
- 스크립트 예시와 같이
start 수명 주기 함수와 초기화 논리를CurrencyBalanceComponent
클래스에 추가합니다. - 장면의 노드에
CurrencyBalanceComponent 를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 프리패브 요소를
CurrencyBalanceItemComponent
의 속성에 바인딩합니다.
xsolla
, 암호: xsolla
). 이 데모 계정은 데모 프로젝트에만 사용할 수 있습니다.- typescript
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
import { XsollaInventory } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
import { CurrencyBalanceItemComponent } from './CurrencyBalanceItemComponent';
const { ccclass, property } = _decorator;
@ccclass('CurrencyBalanceComponent')
export class CurrencyBalanceComponent extends Component {
@property(ScrollView)
itemsList: ScrollView;
@property(Prefab)
currencyBalanceItemPrefab: Prefab;
start() {
XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
XsollaInventory.getVirtualCurrencyBalance(token.access_token, null, itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let currencyBalanceItem = instantiate(this.currencyBalanceItemPrefab);
this.itemsList.content.addChild(currencyBalanceItem);
currencyBalanceItem.getComponent(CurrencyBalanceItemComponent).init(itemsData.items[i]);
}
});
});
}
}
스크립트 작업 결과 예시:

인벤토리 아이템 표시
튜도리얼은 SDK 메소드를 사용하여 사용자 인벤토리에 아이템을 표시하는 방법을 보여줍니다.
아이템 위젯 생성
- 프리패브를 생성합니다. 이렇게 하려면 폴더의 컨텍스트 메뉴에서
Create > Node Prefab 를 선택합니다. - 생성된 프리패브를 엽니다.
- 아래 이미지와 같이 프리패브의 루트에
UITransform
구성 요소를 추가하고 콘텐츠 크기를 설정합니다.

- 다음 UI 요소를 프리패브 하위 개체로 추가하고 해당하는 비주얼을 구성합니다.
- 위젯 배경 이미지
- 인벤토리 아이템 이름
- 인벤토리 아이템 설명
- 아이템 수량
- 아이템 이미지
위젯 구조 예시:

아이템 위젯 스크립트 생성
- InventoryItemComponent 생성을 수행한 후 다음 속성을 추가합니다.
iconSprite
itemNameLabel
itemDescriptionLabel
quantityLabel
- 스크립트 예시와 같이
init
메소드와 초기화 논리를InventoryItemComponent
클래스에 추가합니다. - InventoryItemComponent를 프리패브의 루트 노드에 연결합니다.
- 그림과 같이 프리패브 요소를
InventoryItemComponent
의 속성에 바인딩합니다.

위젯 스크립트 예시(InventoryItemComponent):
- typescript
import { _decorator, assetManager, Component, ImageAsset, Label, Sprite, SpriteFrame, Texture2D } from 'cc';
import { InventoryItem } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
const { ccclass, property } = _decorator;
@ccclass('InventoryItemComponent')
export class InventoryItemComponent extends Component {
@property(Sprite)
iconSprite: Sprite;
@property(Label)
itemNameLabel: Label;
@property(Label)
itemDescriptionLabel: Label;
@property(Label)
quantityLabel: Label;
init(data: InventoryItem) {
this.itemNameLabel.string = data.name;
this.itemDescriptionLabel.string = data.description;
this.quantityLabel.string = data.quantity.toString();
assetManager.loadRemote<ImageAsset>(data.image_url, (err, imageAsset) => {
if(err == null) {
const spriteFrame = new SpriteFrame();
const texture = new Texture2D();
texture.image = imageAsset;
spriteFrame.texture = texture;
this.iconSprite.spriteFrame = spriteFrame;
} else {
console.log(`Can’t load image with URL ${data.image_url}`);
}
});
}
}
페이지 컨트롤러 생성
인벤토리 페이지에 대한 장면을 생성하고 ScrollView
요소를 추가합니다.
페이지 구조 예시:

생성된 InventoryItem
프리패브와 일치하는 ScrollView
를 만들기 위해 크기를 설정하는 방법:
ScrollView
노드와 내부view
노드에서ContentSize
매개 변수 값을 변경합니다.Layout
구성 요소를content
노드에 바인딩하고 이를 설정합니다. 예시에서는 다음과 같은 설정이 선택되어 있습니다.Type == vertical
ResizeMode == Container
인벤토리 페이지 스크립트 구성 요소 생성
- InventoryItemsComponent 생성 작업을 수행한 후 다음 속성을 추가합니다.
itemsScrollView
inventoryItemPrefab
- 스크립트 예시와 같이
start 수명 주기 함수와 초기화 논리를InventoryItemsComponent
에 추가합니다. - 장면의 노드에 InventoryItemsComponent를 추가합니다. 새 노드를 추가하거나 SDK 초기화를 수행하는 동안 추가한
XsollaSettingsManager
구성 요소가 있는 기존 노드를 사용할 수 있습니다. - 그림과 같이 프리패브 요소를
InventoryItemsComponent
의 속성에 바인딩합니다.
xsolla
, 암호: xsolla
). 이 데모 계정은 데모 프로젝트에만 사용할 수 있습니다.- typescript
import { _decorator, Component, instantiate, Prefab, ScrollView } from 'cc';
import { XsollaAuth } from 'db://xsolla-commerce-sdk/scripts/api/XsollaAuth';
import { XsollaInventory } from 'db://xsolla-commerce-sdk/scripts/api/XsollaInventory';
import { InventoryItemComponent } from './InventoryItemComponent';
const { ccclass, property } = _decorator;
@ccclass('InventoryItemsComponent')
export class InventoryItemsComponent extends Component {
@property(ScrollView)
itemsScrollView: ScrollView;
@property(Prefab)
inventoryItemPrefab: Prefab;
start() {
XsollaAuth.authByUsernameAndPassword('xsolla', 'xsolla', false, token => {
XsollaInventory.getInventory(token.access_token, null, itemsData => {
for (let i = 0; i < itemsData.items.length; ++i) {
let inventoryItem = instantiate(this.inventoryItemPrefab);
this.itemsScrollView.content.addChild(inventoryItem);
inventoryItem.getComponent(InventoryItemComponent).init(itemsData.items[i]);
}
});
});
}
}
스크립트 작업 결과 예시:

오자 또는 기타 텍스트 오류를 찾으셨나요? 텍스트를 선택하고 컨트롤+엔터를 누르세요.