출처: https://hybridclr.doc.code-philosophy.com/en/docs/beginner/quickstart

이 튜토리얼은 빈 프로젝트에서 HybridCLR 핫 업데이트를 경험하는 방법을 안내합니다. 단순화를 위해 빌드 대상이 Windows 또는 MacOS Standalone 플랫폼인 경우만 시연합니다.

독립 실행형 플랫폼에서 핫 업데이트 프로세스를 올바르게 실행한 다음 Android 및 iOS 플랫폼에서 핫 업데이트를 시도해 보세요. 프로세스는 매우 유사합니다.

경험 목표

환경 준비

Unity 설치

CAUTION

HybridCLR은 Unity 2019~2022의 모든 LTS 버전을 지원합니다. 현재 사용 중인 버전이 아래 권장 버전에 포함되지 않는 경우 Install HybridCLR 문서를 참조하세요.

select il2cpp modules

IDE 및 관련 컴파일 환경 설치

Unity 핫 업데이트 프로젝트 초기화

핫 업데이트 프로젝트를 처음부터 빌드하는 과정은 지루합니다. 프로젝트 구조, 리소스 및 코드는 hybridclr_trial 프로젝트를 참조할 수 있으며, 해당 저장소 주소는 github 또는 gitee입니다.

프로젝트 생성

빈 Unity 프로젝트를 생성합니다.

ConsoleToScreen.cs 스크립트를 생성합니다.

이 스크립트는 핫 업데이트 시연에 직접적인 영향을 미치지 않습니다. 로그를 화면에 인쇄할 수 있으므로 오류를 찾는 데 편리합니다.

Assets/ConsoleToScreen.cs 스크립트 클래스를 생성하며, 코드는 다음과 같습니다:

using System;
using System. Collections;
using System.Collections.Generic;
using UnityEngine;

public class ConsoleToScreen : MonoBehaviour
{
   
const int maxLines = 50;
   
const int maxLineLength = 120;
   
private string _logStr = "";

   
private readonly List<string>_lines = new List<string>();

   
public int fontSize = 15;

   
void OnEnable() { Application. logMessageReceived += Log; }
   
void OnDisable() { Application. logMessageReceived -= Log; }

   
public void Log(string logString, string stackTrace, LogType type)
    {
       
foreach (var line in logString. Split('\n'))
        {
           
if (line. Length <= maxLineLength)
            {
                _lines. Add(line);
               
continue;
            }
           
var lineCount = line.Length / maxLineLength + 1;
           
for (int i = 0; i < lineCount; i++)
            {
               
if ((i + 1) * maxLineLength <= line.Length)
                {
                    _lines.Add(line.Substring(i * maxLineLength, maxLineLength));
                }
               
else
                {
                    _lines.Add(line.Substring(i * maxLineLength, line.Length - i * maxLineLength));
                }
            }
        }
       
if (_lines. Count > maxLines)
        {
            _lines. RemoveRange(0, _lines. Count - maxLines);
        }
        _logStr =
string. Join("\n", _lines);
    }

   
void OnGUI()
    {
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
           
new Vector3(Screen. width / 1200.0f, Screen. height / 800.0f, 1.0f));
        GUI.Label(
new Rect(10, 10, 800, 370), _logStr, new GUIStyle() { fontSize = Math.Max(10, fontSize) });
    }
}

기본 장면 만들기

핫업데이트 핫 업데이트 모듈 생성

HybridCLR 설치 및 구성하기

com.code-philosophy.hybridclr 패키지를 설치합니다.

메인 메뉴에서 Windows/패키지 관리자를 클릭하여 패키지 관리자를 엽니다. 아래와 같이 Add package from git URL...를 클릭하고 https://gitee.com/focus-creative-games/hybridclr_unity.git 또는 https://github.com/focus-creative -games/hybridclr_unity.git을 입력합니다.

add package

URL에서 패키지를 설치하는 데 익숙하지 않은 경우 giturl에서 설치하기를 참조하세요.

국내 네트워크 사정으로 인해 Unity에서 네트워크 예외가 발생하여 설치에 실패할 수 있습니다. 먼저 com.code-philosophy.hybridclr를 로컬에 복제 또는 다운로드하고 폴더 이름을 com.code-philosophy.hybridclr로 변경한 후 프로젝트의 Packages 디렉토리로 직접 이동합니다.

com.code-philosophy.hybridclr를 초기화합니다.

하이브리드CLR/인스톨러... 메뉴를 열고 설치 버튼을 클릭하여 설치합니다. 약 30초간 기다립니다. 설치가 완료되면 마지막에 설치 성공 로그가 인쇄됩니다.

HybridCLR 구성

HybridCLR/Settings 메뉴를 열고 아래와 같이 HotUpdate 어셈블리를 Hot Update Assemblies 구성 항목에 추가합니다:

settings

Configure PlayerSettings

player settings

Create hot update script

Create Assets/HotUpdate/Hello.cs file, the code content is as follows

using System. Collections;
using UnityEngine;

public class Hello
{
   
public static void Run()
   {
       Debug. Log(
"Hello, HybridCLR");
   }
}

핫 업데이트 부분의 코드가 다른 솔루션처럼 C# 구문에 제한이 있는 것은 아닌지 걱정하실 수 있습니다. HybridCLR은 거의 완벽하게 구현되어 있으며 핫 업데이트 코드에 대한 제한이 거의 없으므로 직접 작성해 보시기 바랍니다.

드문 예외에 대해서는 지원되지 않는 기능를 참조하세요.

핫 업데이트 어셈블리 로드

데모를 단순화하기 위해 http 서버를 통해 핫업데이트.dll을 다운로드하지 않고 스트리밍 자산 디렉토리에 핫업데이트.dll을 직접 넣습니다.

HybridCLR은 네이티브 런타임 구현이므로 Assembly Assembly.Load(byte[])를 호출하여 핫 업데이트 어셈블리를 로드합니다.

Assets/LoadDll.cs 스크립트를 생성한 다음 기본 장면에 게임 오브젝트를 생성하고 LoadDll 스크립트를 마운트합니다.

using HybridCLR;
using System;
using System. Collections;
using System.Collections.Generic;
using System.IO;
using System. Linq;
using System. Reflection;
using System. Threading. Tasks;
using UnityEngine;
using UnityEngine. Networking;
public class LoadDll : MonoBehaviour
{

   
void Start()
    {
     
// In the Editor environment, HotUpdate.dll.bytes has been automatically loaded and does not need to be loaded. Repeated loading will cause problems.
#if !UNITY_EDITOR
        Assembly hotUpdateAss = Assembly.Load(File.ReadAllBytes(
$"{Application.streamingAssetsPath}/HotUpdate.dll.bytes"));
#else
     
// No need to load under Editor, directly find the HotUpdate assembly
        Assembly hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name ==
"HotUpdate");
#endif
    }
}

핫 업데이트 코드 호출

물론 메인 프로젝트는 핫 업데이트 코드를 직접 참조할 수 없습니다. 메인 프로젝트에서 핫 업데이트 어셈블리의 코드를 호출하는 방법에는 여러 가지가 있습니다. 여기서는 리플렉션을 통해 핫 업데이트 코드를 호출합니다.

LoadDll.Start 함수 뒤에 리플렉션 호출 코드를 추가하면 다음과 같이 최종 코드가 완성됩니다:

     

void Start()
    {
     
// In the Editor environment, HotUpdate.dll.bytes has been automatically loaded and does not need to be loaded. Repeated loading will cause problems.
#if !UNITY_EDITOR
        Assembly hotUpdateAss = Assembly.Load(File.ReadAllBytes(
$"{Application.streamingAssetsPath}/HotUpdate.dll.bytes"));
#else
     
// No need to load under Editor, directly find the HotUpdate assembly
        Assembly hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name ==
"HotUpdate");
#endif
   
        Type type = hotUpdateAss. GetType(
"Hello");
        type. GetMethod(
"Run"). Invoke(null, null);
    }

지금까지 전체 핫 업데이트 프로젝트의 생성이 완료되었습니다! ! !

에디터에서 체험판 실행

메인 장면을 실행하면 코드가 정상적으로 작동하고 있음을 나타내는 'Hello, HybridCLR'이 화면에 표시됩니다.

패키징 및 실행

패키징에 성공하고 화면에 'Hello, HybridCLR'이 표시되면 핫 업데이트 코드가 성공적으로 실행된 것입니다!

핫 업데이트 테스트

이것으로 핫 업데이트 체험이 완료되었습니다! ! !