Home > Unity > Netcode > Unity Netcode 따라하기 Golden Path Two

Unity Netcode 따라하기 Golden Path Two
Unity Netcode Unet Networkk

Golden Path Two

Golden Path Two 학습 문서
본 게시글은 해당 문서를 학습하며 정리한 게시글 입니다.

Netcode 설치하기
해당 게시글에 Netcode 설치 및 프로젝트 생성까지 소개 한다.

Hello World 학습하기
해당 게시글에 선행 프로젝트인 Hello World 학습 및 구현 한다.

Golden Path One 학습 문서
해당 게시글은 Golden Path One 학습 정리글입니다.

*앞선 게시글 부터 순차적으로 진행하는 로드맵입니다 선행 프로젝트를 먼저 학습해 주세요.

Server에서 Network 변수 제어하기

Client에서 Server로 변수를 보내 중요 데이터 및 공유 데이터를 Server에서 제어하게끔 만들어야 하는 경우가 있다.
해당 코드는 그러한 기능을 안내한다.

위에 링크한 문서에는 빠트린게 몇몇가지가 있는 것 같다. 이것저것 찾아본 결과 다른 개발자도 이상하게 여기는 것을 보아 누락된 부분이 있는 것 같다.
내가 임의적으로 추가한 코드가 있다.
*추가된 코드는 주석으로 표시해두었다.

NetworkVariableTest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class NetworkVariableTest : NetworkBehaviour
{
    private NetworkVariable<float> ServerNetworkVariable = new NetworkVariable<float>();
    // ClientNetworkVariable 변수 추가
    // public NetworkVariable<float> ClientNetworkVariable = new NetworkVariable<float>();
    private float last_t = 0.0f;

    public override void OnNetworkSpawn()
    {
        if(IsServer)
        {
            ServerNetworkVariable.Value = 0.0f;
            // 변수 초기화 추가
            // ClientNetworkVariable.Value = 0.0f;
            Debug.Log("Server's var initialized to : " + ServerNetworkVariable.Value);
        }
    }

    // Update is called once per frame
    void Update()
    {
        var t_now = Time.time;
        if (IsServer)
        {
            ServerNetworkVariable.Value = ServerNetworkVariable.Value + 0.1f;
            if(t_now - last_t > 0.5f)
            {
                last_t = t_now;
                Debug.Log("Server set its var to: " + ServerNetworkVariable.Value + ", has client var at: " + ClientNetworkVariable.Value);
            }
        }
        // Server가 아닌경우 ServerRpc 메서드 호출 추가
        //else
        //{
        //    this.SubmitNetworkVariableRequestServerRpc();
        //}
    }

    // Client 변수에 값 추가.
    //[ServerRpc]
    //void SubmitNetworkVariableRequestServerRpc(ServerRpcParams rpcParams = default)
    //{
    //    ClientNetworkVariable.Value = ClientNetworkVariable.Value + 0.1f;
    //}
}

간단한 설명은 주석에 적어두었다.

해당 코드를 Player Prefab에 추가해주고 Build 한뒤 Server와 Client로 실행하면 해당 결과가 나온다.
*Editor와 .exe 파일 간에는 값을 주고받는 속도의 격차가 크다. 나는 .exe 파일로만 테스트 했다.

실행결과
UnloadTime: 0.673400 ms
Server's var initialized to : 0
Server set its var to: 0.1, has client var at: 0
Server set its var to: 2.999999, has client var at: 2.4
Server set its var to: 5.999997, has client var at: 5.399997
Server set its var to: 8.999998, has client var at: 8.399996
Server set its var to: 12.10001, has client var at: 11.50001
Server set its var to: 15.10002, has client var at: 14.50002
Server set its var to: 18.10003, has client var at: 17.50003
Server set its var to: 21.10004, has client var at: 20.50004
Server set its var to: 24.10006, has client var at: 23.50005
...

잘 나오는 것을 볼 수 있다. Debug.Log로 출력되는 Log는 따로 설정하지 않는 이상
[C드라이브] - [Users] - [사용자 이름] - [Appdata] - [localNow] - [빌드시 설정한 회사이름] - [프로젝트 이름] 폴더에 들어가보면 txt 파일이 있을 것이다.

NetworkTransformTest
using System;
using UnityEngine;
using Unity.Netcode;
public class NetworkTransformTest : NetworkBehaviour
{
    void Update()
    {
        if(IsServer)
        {
            float theta = Time.frameCount / 10.0f;
            transform.position = new Vector3((float)Math.Cos(theta), 1f, (float)Math.Sin(theta));
        }
    }
}

해당 코드를 Player Prefab에 추가해주기 전 먼저 추가했던 NetworkVariableTest.cs 컴포넌트는 비활성화 해준다. 딱히 상관은 없지만 불필요하다.

Player Prefab에 추가해준 후 Build 한뒤 Server와 Client로 실행하면 빙글 빙글 도는 Player를 볼 수 있다.
*Editor와 .exe 파일 간에는 값을 주고받는 속도의 격차가 크다. 나는 .exe 파일로만 테스트 했다.

RpcTest
using System;
using UnityEngine;
using Unity.Netcode;
public class RpcTest : NetworkBehaviour
{

    public override void OnNetworkSpawn()
    {
        if(IsClient)
        {
            TestServerRpc(0);
        }
    }

    [ClientRpc]
    void TestClientRpc(int value)
    {
        if(IsClient)
        {
            Debug.Log("Client Received the RPC #" + value);
            TestServerRpc(value + 1);
        }
    }

    [ServerRpc]
    void TestServerRpc(int value)
    {
        Debug.Log("Server Received the RPC #" + value);
        TestClientRpc(value);
    }
}

해당 코드는 앞선 NetworkVariableTest 코드의 기능과 비슷하다.
다른 점은 변화된 인자를 매개변수로 넘겨 주고 받는 점이다.

해당 코드를 Palyer Prefeb에 Add Component 해준 후 Build하여 실행 한다.
상태를 Host로 설정하여 log 를 확인하면

UnloadTime: 0.946200 ms
Server Received the RPC #0
Client Received the RPC #0
Server Received the RPC #1
Client Received the RPC #1
Server Received the RPC #2
Client Received the RPC #2
Server Received the RPC #3
Client Received the RPC #3
Server Received the RPC #4
Client Received the RPC #4
Server Received the RPC #5
...

위와 같은 log를 확인 할 수 있다. log를 보는 방법은 앞서 소개했다.

Unity에서 제공하는 기본적은 Netcode 사용 안내는 여기까지 이다.
이 외에는 샘플 프로젝트를 통한 실습이 있다.