이번 시간에는 React에서 Unity로 데이터 통신을 할 수 있는 방법에 대해 소개하고자 한다.
react-unity-webgl 패키지를 이용하면 React에서 Unity로 통신을 할 수 있다.
이 프로젝트에서는 다음을 구현하고자 한다.
● React에 string 타입 prompt를 Unity에 보내기
● Unity 내 텍스트 박스에 React에 받은 prompt 표시하기
01. Unity Prompt를 띄울 GUI 구현 및 통신 준비
Unity 내 Prompt를 보여줄 TestMeshPro 오브젝트를 생성하고 간단하게 GUI를 구현해준다.
또한 필요한 컴포넌트 ButtomManager.cs와 PromptManager.cs 스크립트를 생성한다.
02. PromptManager 스크립트에서 ReceivePrompt 함수 생성
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;
public class PromptManager : MonoBehaviour
{
[SerializeField]
string prompt;
[SerializeField]
private TextMeshProUGUI promptGUI;
public void ReceivePrompt(string _prompt)
{
prompt = _prompt;
promptGUI.text = prompt;
}
}
PromptManager.cs 스크립트에 RecevicePrompt 함수를 다음과 같이 선언하여 React에서 Prompt 데이터를 받을 시 text 필드에 띄어 줄 수 있게 구현하면 Unity에서 준비는 끝난다.
03. React에서 react-unity-webgl을 이용하여 Unity 통신
import logo from './logo.svg';
import './App.css';
import React, { useCallback, useState } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const [prompt, setPrompt] = useState("Hello world");
const { unityProvider, sendMessage} =
useUnityContext({
loaderUrl: "Build/Build.loader.js",
dataUrl: "Build/Build.data",
frameworkUrl: "Build/Build.framework.js",
codeUrl: "Build/Build.wasm",
});
function send_prompt() {
sendMessage("PromptManager", "ReceivePrompt", prompt);
}
return (
<div className="App">
<h1>{prompt}</h1>
<button onClick={send_prompt}>Prompt Unity 전송</button>
<br/>
<Unity style={{
width: '83%',
height: '100%',
justifySelf: 'center',
alignSelf: 'center',
}} unityProvider={unityProvider} />
</div>
);
}
export default App;
Unity에 보낼 prompt를 "Hello world"라고 임의로 지정해준 후 react-unity-webgl의 sendMessage() 함수를 통해 Unity의 PromptManager 스크립트 내 ReceivePrompt 함수를 호출해주면 된다. 함수가 매개변수를 받는 다면 뒤에 매개변수를 같이 넣어주면 된다.
참고자료
https://react-unity-webgl.dev/
React Unity WebGL
Bringing your Unity Games to the Web since 2017!
react-unity-webgl.dev
'프로그래밍 > WebGL' 카테고리의 다른 글
[WebGL] Unity WebGL InputField 한글 입력 (0) | 2024.01.20 |
---|---|
[WebGL] Unity에서 React 통신하기 (0) | 2024.01.20 |
[WebGL] React에 Unity 콘텐츠 퍼블리시 (0) | 2024.01.20 |
[WebGL] react-unity-webgl 소개 (0) | 2024.01.20 |