CREATE YOUR WORLD
Economy
Product API 활용 예제
18분
다음은 product api를 사용하여 월드 통화 및 월드 상 품을 관리하는 예입니다 이 예제는 제품 api에 대한 기본적인 이해를 돕고 서버와 클라이언트 간의 메시지를 송수신하는 구현을 가능하게 하여 월드 통화 및 월드 상품의 획득와 차감을 쉽게 테스트할 수 있도록 합니다 이 예제에는 월드 통화 및 월드 상품 클라이언트 스크립트에 대한 설명이 포함되어 있으며, 모든 서버 측 처리를 처리하는 통합 서버 스크립트가 뒤따르며 다음 기능이 포함됩니다 월드 통화 획득 월드 통화 차감 통화 차감 없이 월드 상품 획득 월드 상품 차감 월드 통화 획득 및 차감 아래는 월드 통화 획득 및 차감을 관리하는 전체 클라이언트 코드와 이를 구현하는 방법입니다 통화 클라이언트 스크립트 currencymanagersample import { button, text } from 'unityengine ui'; import { zepetoscriptbehaviour } from 'zepeto script' import { localplayer, zepetoplayers } from 'zepeto character controller'; import { room, roomdata } from 'zepeto multiplay'; import { zepetoworldmultiplay } from 'zepeto world'; export default class currencymanagersample extends zepetoscriptbehaviour { public currencyid string; public increasequantity number; public decreasequantity number; public increasecurrencybtn button; public decreasecurrencybtn button; public balancetext text; public multiplay zepetoworldmultiplay; private localplayer localplayer; start() { zepetoplayers instance onaddedlocalplayer addlistener(() => { this localplayer = zepetoplayers instance localplayer; this loadcurrencybalance(this currencyid); }); // 통화 ui 업데이트를 위한 방 참여 이벤트 처리 this multiplay roomjoined += (room room) => { room addmessagehandler("synccurrencyinfo", (message currencymessage) => { const currentcurrencyid = message currencyid; const currentquantity = message quantity; this balanceuiupdate(currentcurrencyid, currentquantity); }); }; // 통화 증가 버튼 이벤트 리스너 크레딧 요청 this increasecurrencybtn onclick addlistener(() => { const data = new roomdata(); data add("currencyid", this currencyid); data add("quantity", this increasequantity); this multiplay room? send("creditcurrency", data getobject()); }) // 통화 감소 버튼 이벤트 리스너 차감 요청 this decreasecurrencybtn onclick addlistener(() => { const data = new roomdata(); data add("currencyid", this currencyid); data add("quantity", this decreasequantity); this multiplay room? send("debitcurrency", data getobject()); }) } // 지정된 통화의 현재 금액 요청 private loadcurrencybalance(currentcurrencyid string) { this multiplay room? send("loadbalance", currentcurrencyid); } // 현재 통화의 수량을 반영하도록 ui 업데이트 private balanceuiupdate(currentcurrencyid string, currentquantity number) { this balancetext text = currentquantity tostring(); } } // 통화 동기화 메시지 인터페이스 interface currencymessage { currencyid string, quantity number, } 통화 클라이언트 스크립트 설명 캐릭터가 로드되면, 서버에 기존 통화 잔액을 로드하기 위해 방 메시지가 전송됩니다 그런 다음 서버에서 수신한 잔액 정보를 기반으로 ui가 업데이트됩니다 this multiplay room? send("loadbalance", currentcurrencyid); 메시지 교환을 용이하게 하기 위해, currencymessage 인터페이스가 정의됩니다 interface currencymessage { currencyid string, quantity number, } 사용자가 통화를 증가시키거나 감소시킬 때, 그들은 서버에 room 메시지로 요청을 보냅니다 어떤 통화를 얼마나 증가시키거나 감소시킬지를 포함한 데이터가 포함됩니다 this multiplay room? send("creditcurrency", data getobject()); this multiplay room? send("debitcurrency", data getobject()); 서버는 통화의 증가 또는 감소를 처리한 후, 최종 잔액 정보를 클라이언트에 보냅니다 클라이언트는 이 정보를 수신하고 ui를 업데이트합니다 product api 활용 예제 docid\ f2bjp1ddm1unnutkykznk this multiplay roomjoined += (room room) => { room addmessagehandler("synccurrencyinfo", (message currencymessage) => { const currentcurrencyid = message currencyid; const currentquantity = message quantity; this updatebalanceui(currentcurrencyid, currentquantity); }); }; 월드 상품의 획득 및 차감 아래는 월드 제품 획득 및 차감을 관리하는 전체 클라이언트 코드와 이를 구현하는 방법입니다 제품 클라이언트 스크립트 productmanagersample import { button, text } from 'unityengine ui'; import { zepetoscriptbehaviour } from 'zepeto script' import { localplayer, zepetoplayers } from 'zepeto character controller'; import { room, roomdata } from 'zepeto multiplay'; import { zepetoworldmultiplay } from 'zepeto world'; import { inventoryrecord, inventoryservice } from 'zepeto inventory'; import { waituntil } from 'unityengine'; export default class productmanagersample extends zepetoscriptbehaviour { public productid string; public productaddquantity number; public acquireitembtn button; public useitembtn button; public itemcounttext text; public multiplay zepetoworldmultiplay; private localplayer localplayer; start() { zepetoplayers instance onaddedlocalplayer addlistener(() => { this localplayer = zepetoplayers instance localplayer; this startcoroutine(this refreshproductui()); }); // 제품 ui 업데이트를 위한 방 참여 이벤트 처리 this multiplay roomjoined += (room room) => { room addmessagehandler("syncproductinfo", (message productmessage) => { this startcoroutine(this refreshproductui()); }); }; // 아이템 획득 버튼 이벤트 리스너 제품 추가 this acquireitembtn onclick addlistener(() => { const data = new roomdata(); data add("productid", this productid); data add("quantity", this productaddquantity); this multiplay room? send("addproduct", data getobject()); }) // 아이템 사용 버튼 이벤트 리스너 제품 사용 this useitembtn onclick addlistener(() => { const data = new roomdata(); data add("productid", this productid); data add("quantity", 1); this multiplay room? send("useproduct", data getobject()); }) } private refreshproductui() { const request = inventoryservice getasync(this productid); yield new waituntil(() => request keepwaiting == false); // 요청이 성공하면 제품 ui를 업데이트합니다 if (request responsedata issuccess) { this updateitemcounttext(request responsedata product); } else { console log("제품 아이템 로드 실패 "); } } private updateitemcounttext(item inventoryrecord) { if (item != null) { this itemcounttext text = item quantity tostring(); } else { this itemcounttext text = "0"; } } } // 제품 메시지 인터페이스 interface productmessage { productid string, productaction productaction, } // 제품 행동 유형을 정의하는 열거형 export enum productaction { use, add, } 제품 클라이언트 스크립트 설명 캐릭터가 로드될 때, inventoryservice 를 사용하여 zepeto inventory https //developer zepeto me/docs/product/namespaces/zepeto inventory/ 의 초기 제품 인벤토리를 로드합니다 그런 다음 ui를 업데이트합니다 private refreshproductui() { const request = inventoryservice getasync(this productid); yield new waituntil(() => request keepwaiting == false); if (request responsedata issuccess) { this updateitemcounttext(request responsedata product); } else { console log("제품 아이템 로드 실패 "); } } 메시지를 보내고 받으려면, productmessage 인터페이스를 정의합니다 productaction 열거형을 예제 구현을 위해 정의합니다 interface productmessage { productid string, productaction productaction, } export enum productaction { 사용, 추가, } 제품을 증가시키거나 감소시킬 때, 해당 데이터를 서버에 룸 메시지로 보냅니다 어떤 제품을 얼마나 증가시키거나 감소시킬지에 대한 데이터가 포함됩니다 this multiplay room? send("addproduct", data getobject()); this multiplay room? send("useproduct", data getobject()); 제품 변경을 처리한 후, 서버는 최종 재고 정보를 클라이언트에 전송하여 ui를 업데이트합니다 product api 활용 예제 docid\ f2bjp1ddm1unnutkykznk this multiplay roomjoined += (room room) => { room addmessagehandler("syncproductinfo", (message productmessage) => { this startcoroutine(this refreshproductui()); }); }; 일반적으로, 월드 제품은 구매를 위해 화폐가 필요합니다 이 경우, 가이드를 참조하여 제품 구매 버튼 으로 쉽게 판매할 수 있습니다 내 월드로 돈벌기! 아이템과 재화 세팅하기 docid\ bi1unmnwhaplvxg21ytso 서버 스크립트 아래는 월드 통화와 제품을 관리하는 전체 서버 코드와 이를 구현하는 방법입니다 전체 서버 스크립트 import { sandbox, sandboxoptions, sandboxplayer } from "zepeto multiplay"; import { loadcurrency } from "zepeto multiplay currency"; import { loadinventory } from "zepeto multiplay inventory"; export default class extends sandbox { async oncreate(options sandboxoptions) { // 통화 //통화 로딩 요청 this onmessage("loadbalance", (client, message string) => { this loadbalance(client, message); }); //크레딧 추가 요청 this onmessage("creditcurrency", (client, message currencymessage ) => { const currencyid = message currencyid; const quantity = message quantity; this addcredit(client, currencyid, quantity); }); //크레딧 차감 요청 this onmessage("debitcurrency", (client, message currencymessage ) => { const currencyid = message currencyid; const quantity = message quantity; this ondebit(client, currencyid, quantity); }); // 제품 //아이템 추가 요청 this onmessage("addproduct", (client, message any) => { const productid = message productid; const quantity = message quantity; this addproduct(client, productid, quantity); }); //아이템 사용 요청 this onmessage("useproduct", (client, message any) => { const productid = message productid; const quantity = message quantity; this useproduct(client, productid, quantity); }); } async addcredit(client sandboxplayer, currencyid string, quantity number) { try { const currency = await loadcurrency(client userid); await currency credit(currencyid, quantity); this loadbalance(client, currencyid); } catch (e) { console error(`addcredit error ${e}`); } } async ondebit(client sandboxplayer, currencyid string, quantity number) { try { const currency = await loadcurrency(client userid); if (await currency debit(currencyid, quantity) === true) { this loadbalance(client, currencyid); } else { console error("debitcredit error 통화 부족"); } } catch (e) { console error(`debitcredit error ${e}`); } } async loadbalance(client sandboxplayer, currencyid string) { try { const currency = await loadcurrency(client userid); let balancesobject = await currency getbalances(); let balancesmap map\<string, number> = new map(object entries(balancesobject)); const specificcurrencyid = currencyid; const specificbalance = balancesmap get(specificcurrencyid) ?? 0; const currencysync currencymessage = { currencyid specificcurrencyid, quantity specificbalance } client send("synccurrencyinfo", currencysync); } catch (e) { console error(`loadbalance error ${e}`); } } async addproduct(client sandboxplayer, productid string, quantity number) { try { const inventory = await loadinventory(client userid); await inventory add(productid, quantity); const productmessage productmessage = { productid productid, productaction productaction add } client send("syncproductinfo", productmessage); } catch (e) { console error(`addproduct error ${e}`); } } async useproduct(client sandboxplayer, productid string, quantity number) { try { const inventory = await loadinventory(client userid); await inventory use(productid, quantity); const productmessage productmessage = { productid productid, productaction productaction use } client send("syncproductinfo", productmessage); } catch (e) { console error(`useproduct error ${e}`); } } onjoin(client sandboxplayer) { // 입장 시 로직 } ontick(deltatime number) void { // 틱 로직 } onleave(client sandboxplayer, consented? boolean) { // 퇴장 처리 로직 } } // 통화 메시지 인터페이스 interface currencymessage { currencyid string, quantity number, } // 제품 메시지 인터페이스 interface productmessage { productid string, productaction productaction, } // 제품 액션 유형 정의를 위한 열거형 export enum productaction { use, add, } 서버 스크립트 설명 월드 통화를 관리하려면 zepeto multiplay currency https //developer zepeto me/docs/multiplay server/namespaces/zepeto multiplay currency/ 사용하려면 currency credit() 및 currency debit() 를 사용하여 원하는 통화의 잔액을 증가시키거나 감소시킵니다 이후, currency getbalances() 를 호출하여 각 통화의 현재 잔액을 가져옵니다 currency credit(currencyid, quantity); currency debit(currencyid, quantity); currency getbalances(); 월드 상 품을 관리하려면 zepeto multiplay inventory https //developer zepeto me/docs/multiplay server/namespaces/zepeto multiplay inventory 사용하려면 inventory add() 및 inventory use() 를 사용하여 원하는 통화의 잔액을 증가시키거나 감소시킵니다 inventory add(productid, quantity); inventory use(productid, quantity); 클라이언트의 통화 및 제품 증가 또는 감소 요청을 처리합니다 사용 loadbalance() 를 사용하여 zepeto studio에 등록된 통화 정보를 가져옵니다 여러 통화가 있는 경우 특정 통화 id 값에 조건을 걸어 해당 통화의 잔액만 가져올 수 있습니다 최종 잔액 값을 클라이언트에게 방 메시지로 전달합니다