Client/Unity

Unity Protobuf 설치

Juzdalua 2024. 9. 1. 14:36

21.3버전을 사용했다.

 

 

1. 컴파일러 다운로드

https://github.com/protocolbuffers/protobuf/releases?q=visual+studio&expanded=true

 

Releases · protocolbuffers/protobuf

Protocol Buffers - Google's data interchange format - protocolbuffers/protobuf

github.com

 

2. 라이브러리 다운로드

dll파일 4개 다운로드한다.

https://www.nuget.org/packages/Google.Protobuf/3.21.3#supportedframeworks-body-tab

https://www.nuget.org/packages/System.Memory/#supportedframeworks-body-tab

https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/#supportedframeworks-body-tab

https://www.nuget.org/packages/System.Buffers/#supportedframeworks-body-tab

 

 

3. dll파일 유니티 프로젝트로 복사

netstandard2.0 버전을 사용했다.

unity2022.3.24f1 버전

 

 

4. 컴파일러 위치 이동

폴더 구조

5. 컴파일러 실행을 위한 배치파일 세팅

// GenPacket.bat

Rem Path Setting
pushd %~dp0

Rem Compile
protoc -I=./ --csharp_out=./ ./Enum.proto
protoc -I=./ --csharp_out=./ ./Struct.proto
protoc -I=./ --csharp_out=./ ./Protocol.proto

Rem Error -> Pause cmd
IF ERRORLEVEL 1 PAUSE

Rem Excute bat -> Make file -> Copy with folder
XCOPY /Y Enum.cs "../../../Assets/Scripts/Protobuf\"
XCOPY /Y Struct.cs "../../../Assets/Scripts/Protobuf\"
XCOPY /Y Protocol.cs "../../../Assets/Scripts/Protobuf\"

DEL /Q /F *.cs

PAUSE

 

6. 배치파일 실행

배치파일을 실행하면 컴파일러를 실행한다.

컴파일러가 실행되면 .proto파일을 .cs파일로 생성하고 정해진 위치에 복사한다.

생성된 .cs파일을 활용해 작업을 진행한다.

 

7. 예제

// Protocol.proto

syntax = "proto3"; // version
package Protocol; // namespace

import "Enum.proto";
import "Struct.proto";

import "google/protobuf/timestamp.proto";
option csharp_namespace = "Google.Protobuf.Protocol";

message S_CHAT
{
	uint64 playerId = 1;
	string msg = 2;
}
using Google.Protobuf.Protocol;
using System;
using Google.Protobuf;

 void protobufTestCreateAndSerialize()
 {
     S_CHAT chat = new S_CHAT
     {
         PlayerId = 1,
         Msg = "Hi",
     };

     byte[] data = chat.ToByteArray();
     Console.WriteLine($"Serialized Player Data: {BitConverter.ToString(data)}");
 }

 void protobufTestDeserializeAndUse(byte[] data)
 {
     S_CHAT chat = S_CHAT.Parser.ParseFrom(data);

     Console.WriteLine($"Player ID: {chat.PlayerId}");
     Console.WriteLine($"Message: {chat.Msg})");
 }