개발/C#, Unity, AR, VR

유니티 WebGL 웹에 붙이고, 웹 페이지 데이터 유니티로 전달하기

미드라이너 2021. 11. 4. 20:21

유니티 웹상에 띄우기는 이전글로 확인해주세요

이전 글을 참고해 주세요

[Node.js] 유니티 WebGL 웹에서 유니티 띄우기 :: 에러 로그 (tistory.com)

 

[Node.js] 유니티 WebGL 웹에서 유니티 띄우기

유니티 WebGL 빌드 유니티 상단에 File 메뉴에서 Build Setting을 눌러줍니다 Build Setting에서 WebGL을 누르고 변경해줍니다 이후 Build를 눌러 프로젝트를 빌드해줍니다. 웹(node.js) 적용 설명은 node.js..

wls3189.tistory.com

 

유니티 프로젝트를 만들고, C# 스크립트 생성

프로젝트 생성 후, C#스크립트를 한개 생성해줍니다.

한글 폰트 지정 및 스크립트 장착

텍스트 오브젝트를 선택하여 Font를 지정해줍니다. (무료 폰트 인터넷에 많이 있으니 한글 폰트를 지정해줍시다.)

- 한글 폰트 미지정 시 WebGL에서 한글이 안나옵니다. (유니티 자체에서는 한글이 있는 폰트를 자동으로 선택해서 보여줘서 보인다고 함)

 

작성한 스크립트를 오브젝트에 붙여줍니다 (저는 "Sphere" 오브젝트에 붙였습니다. 스크립트로 캔버스의 UI Text를 끌어서 지정해주었습니다.)

 

이전 글을 참고하여 유니티 프로젝트를 Build 하고, 생성된 파일을 웹 프로젝트에 포함시킵니다.

[Node.js] 유니티 WebGL 웹에서 유니티 띄우기 :: 에러 로그 (tistory.com)

 

[Node.js] 유니티 WebGL 웹에서 유니티 띄우기

유니티 WebGL 빌드 유니티 상단에 File 메뉴에서 Build Setting을 눌러줍니다 Build Setting에서 WebGL을 누르고 변경해줍니다 이후 Build를 눌러 프로젝트를 빌드해줍니다. 웹(node.js) 적용 설명은 node.js..

wls3189.tistory.com

 

웹에서 유니티에 데이터 전달하기

전체 index.html 코드

우선 유니티 빌드를 통해서 생성된 index.html 파일을 수정한 전체 index.html 코드

- 그대로 가져다 쓰면 정상 동작 하지 않습니다.

<!DOCTYPE html>
<html lang="en-us">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Unity WebGL Player | WebGL_Test</title>
  <link rel="shortcut icon" href="TemplateData/favicon.ico">
  <link rel="stylesheet" href="TemplateData/style.css">
  <script src="TemplateData/UnityProgress.js"></script>
  <script src="Build/UnityLoader.js"></script>
  <script>
    var gameInstance = UnityLoader.instantiate("gameContainer", "Build/TestApp.json", {onProgress: UnityProgress});
  </script>
</head>
<body>
<div class="webgl-content">
  <div id="gameContainer" style="width: 960px; height: 600px"></div>
  <div class="footer">
    <div class="webgl-logo"></div>
    <div class="fullscreen" onclick="gameInstance.SetFullscreen(1)"></div>
    <div class="title">WebGL_Test</div>
  </div>
</div>

<div id="btn1" onclick="btn1()">버튼1</div>
<div id="btn2" onclick="btn2()">버튼2</div>
</body>

<script>
  function btn1(){
    gameInstance.SendMessage("Sphere", "setText1", 77.7);
  }
  function btn2(){
    dataSet = {data1: "데이터1", data2: "데이터2"}
    gameInstance.SendMessage("Sphere", "setText2", JSON.stringify(dataSet));
  }
</script>

</html>

 

순차적 적용 내용-----

생성된 index.html 파일중 gameInstance 를 통해 SendMessage 함수로 유니티로 데이터를 전달하게 됩니다.

 

모바일 포함된 경우에는 index.html 파일이 아래와 같이 모양이 약간 다릅니다.

생성된 파일중 index.html 파일의 하단 script 태그 내부에 unityInstance 를 통해 데이터를 유니티로 전달할 수 있게 됩니다.

다른 위치에서 사용하기 위해 gameInstance 변수에 담았습니다.

 

gameInstance.SendMessage("물체이름", "함수이름", 데이터)

물체 이름은 유니티 내 오브젝트의 이름이고, 함수이름은 C#스크립트에 작성한 함수의 이름이고, 데이터는 함수에 정의된 매개변수 타입으로 전송하시면 됩니다. (배열은 전송 불가능 >> 데이터 여러개 보낼때는 최하단 내용 참고)

 

웹 서버를 실행시키고 접속합니다.

웹 상의 버튼1, 버튼2를 누르면 TextUI의 값이 변경됩니다.

버튼 1 누름

 

여러개의 데이터를 보낼때

LitJson.dll 파일을 다운받아 유니티 프로젝트 내 Plugins 폴더에 넣어둡니다.

 

유니티의 C#스크립트에서 먼저 제이슨 데이터를 받을수 있도록 변경합니다.

using LitJson으로 Plugins 폴더의 LitJson을 불러옵니다.

setText2(string) 함수를 선언하며 제이슨 문자열을 받아 처리하는 함수를 만들어줍니다.

LitJson 라이브러리의 JsonData 객체를 생성하여 JsonMapper.ToObject 함수를 사용하여 받아온 Json문자열을 변환합니다.

 

이후 데이터는 jsonPlayer 변수에 담겨서, jsonPlayer["데이터 명"]; 형식으로 사용합니다.

문자열로 간단히 변환하기 위해 "" 문자열 + jsonPlayer["data1"]; 형식으로 사용하였습니다.

 

다시 유니티 프로젝트 빌드하여 웹 서버에 포함시킵니다.

유니티의 전체 C# 스크립트 소스

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using LitJson;

public class Web_controller : MonoBehaviour
{
    public Text text1;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    public void setText1(double value)
    {
        text1.text = "데이터 한개 : " + value + "입니다";
    }

    public void setText2(string jsonString)
    {
        JsonData jsonPlayer = JsonMapper.ToObject(jsonString);

        string text_val1 = "" + jsonPlayer["data1"];
        string text_val2 = "" + jsonPlayer["data2"];

        text1.text = "data1 : " + text_val1 + "\n"
                    + "data2 : " + text_val2;

        //text1.text = "data1 : " + jsonPlayer["data1"] + "\n" + "data2 : " + jsonPlayer["data2"];
    }

}

 

웹 서버로 돌아와서 index.html 파일에 btn2() 함수를 추가해줍니다

데이터(dataSet)를 Dictionary 형태로 만들어 줍니다

해당 데이터는 버튼2를 눌렀을때 SendMessage 함수를 통해 JSON.stringify() 함수를 사용하여 문자열로 변환시켜 전송됩니다.

웹서버를 실행시키고 접속하여, 버튼 2를 누르면 전송한 {data1: "데이터1", data2: "데이터2"}가 유니티의 Json 문자열로 받아서 처리됐습니다.

버튼 2 누름