Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

행복한 개구리

Unity 복습 21.05.11. PUN2 - 로비 구현2 본문

Unity/복습

Unity 복습 21.05.11. PUN2 - 로비 구현2

HappyFrog 2021. 5. 12. 00:40
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

public class Launcher : MonoBehaviourPunCallbacks
{
    #region Private Serializable Fields
    #endregion

    #region Private Fields    
    string gameVersion = "1";
    #endregion

    #region MonoBehaviour CallBacks    
    void Awake()
    {
        PhotonNetwork.AutomaticallySyncScene = true;
    }

    void Start()
    {
        Connect();
    }
    #endregion

    #region Public Methods
    public void Connect()
    {
        if (PhotonNetwork.IsConnected)
        {
            PhotonNetwork.JoinRandomRoom();
        }
        else
        {
            PhotonNetwork.GameVersion = gameVersion;
            PhotonNetwork.ConnectUsingSettings();
        }
    }
    #endregion

    #region MonoBehaviourPunCallbacks Callbacks
    public override void OnConnectedToMaster()
    {
        Debug.Log("PUN Basics Tutorial/Launcher: OnConnectedToMaster() was called by PUN");
        PhotonNetwork.JoinRandomRoom();
        //base.OnConnectedToMaster();
    }

    public override void OnJoinRandomFailed(short returnCode, string message)
    {
        Debug.Log("PUN Basics Tutorial/Launcher:OnJoinRandomFailed() was called by PUN. No random room available, so we create one.\nCalling: PhotonNetwork.CreateRoom");
        //base.OnJoinRandomFailed(returnCode, message);
        PhotonNetwork.CreateRoom(null, new RoomOptions());
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("PUN Basics Tutorial/Launcher: OnJoinedRoom() called by PUN. Now this client is in a room.");
        //base.OnJoinedRoom();
    }

    public override void OnDisconnected(DisconnectCause cause)
    {
        Debug.LogWarningFormat("Pub Basics Tutorial/Launcher: OnDisconnected() was called by PUN with reason {0}", cause);
        //base.OnDisconnected(cause);
    }
    #endregion
}

MonoBehaviourPunCallbacks Callbacks부분을 보면 상속받아 덮어쓰는 메서드가 4가지가 있는데

 

1. OnConnectedToMaster가 실행되며 실행됨을 알리고 랜덤룸에 참가하는 메서드를 사용한다.

2. 만약 랜덤룸이 없거나 들어갈 수 없는상태라면  OnJoinRandomFailed를 실행하며 로그를 출력하고 방을 만든다.

3. 1을 실행하고 바로 방에 입장을 하거나 2를 거쳐 방을 생성한 뒤 그 방에 입장을 하게되면 OnJoinedRoom이 실행된다.

4. 연결이 끊기면 OnDisconnected를 통해 원인을 출력해준다.

 

-아직은 튜토리얼을 따라하고있어서 모든 상속받는 내용들을 주석처리했다.

플레이시 로그가 뜬다.

[SerializeField]를 사용하면 그 아래코드는 Private제한자여도 인스펙터에 노출된다.

반대로 [HideInInspector]를 사용하면 그 아래코드는 public이어도 인스펙터창에 노출되지 않는다.

 

* 신기한 부분은 위 스크립트부분에서 설명한 4부분만 사용하는데 Start의 Connect를 지우면 아무것도 출력되지 않는다.

-----------------------------------------------------------------------------------------------------------------------------------

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;

[RequireComponent(typeof(InputField))]
public class PlayerNameInputField : MonoBehaviour
{
    #region Private Constants
    const string playerNamePrefKey = "PlayerName";
    #endregion

    #region MonoBehaviour CallBacks
    void Start()
    {
        string defaultName = string.Empty;
        InputField _inputField = this.GetComponent<InputField>();
        if(_inputField != null)
        {
            if (PlayerPrefs.HasKey(playerNamePrefKey))
            {
                defaultName = PlayerPrefs.GetString(playerNamePrefKey);
                _inputField.text = defaultName;
            }
        }
        PhotonNetwork.NickName = defaultName;
    }
    #endregion

    #region Public Methods
    public void SetPlayerName(string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            Debug.LogError("Plyaer Name is null or empty");
            return;
        }
        PhotonNetwork.NickName = value;

        PlayerPrefs.SetString(playerNamePrefKey, value);
    }
    #endregion
}

코드 자체는 어렵진 않은편이다.

 

1. PlayerPrefs의 key로 쓸 playerNamePrefKey를 const로 변하지않게 선언해두고

2. Start하면서 기본값을 빈 값으로 불러오며

3. SetPlayerName의 이벤트를 통해 InputField의 값이 Null 또는 Empty일 때 에러를 내며 정지한다.

4. 하지만 입력된 값이 있다면 그 값은 PlayerPrefs의 playerNamePrefKey라는 Key의 값(Value)이 된다.

 

우리가 딕셔너리로 데이터나 정보를 연동하는것과 비슷해보인다. 그리고 이를 통해 저장된 값은 다음에 실행할 때 Start메서드를 통해 InputField에 불러와진다.

보다시피 입력한 값이 사라지지않고 남아있다. 하지만 InputField가 공백이 되는 순간 에러가 난다.(에러처리를 했기 때문)

 

PlayerPrefs에 주어진 키가 있다면 참, 아니면 거짓을 반환

 

Photon PUN Manual

클래스 상단에 위치한 코드의 뜻

 

C# Microsoft Docs

const도 오랜만에 만나서 찾아봤다. 변수가 아닌 '상수'를 선언할 때 사용한다고 한다.

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

using Photon.Pun;
using Photon.Realtime;

public class Launcher : MonoBehaviourPunCallbacks
{       
    [Tooltip("The maximum number of players per room. When a room is full, it can't be joined by new players, and so new room will be created")]
    [SerializeField]
    private int maxPlayersPerRoom = 4;
    #region Private Serializable Fields
    #endregion

    #region Private Fields    
    string gameVersion = "1";
    #endregion

    #region MonoBehaviour CallBacks    
    void Awake()
    {
        PhotonNetwork.AutomaticallySyncScene = true;
    }

    void Start()
    {
        
    }
    #endregion

    #region Public Methods
    public void Connect()
    {
        if (PhotonNetwork.IsConnected)
        {
            PhotonNetwork.JoinRandomRoom();
        }
        else
        {
            PhotonNetwork.GameVersion = gameVersion;
            PhotonNetwork.ConnectUsingSettings();
        }
    }
    #endregion

    #region MonoBehaviourPunCallbacks Callbacks
    public override void OnConnectedToMaster()
    {
        Debug.Log("PUN Basics Tutorial/Launcher: OnConnectedToMaster() was called by PUN");
        PhotonNetwork.JoinRandomRoom();
        //base.OnConnectedToMaster();
    }

    public override void OnJoinRandomFailed(short returnCode, string message)
    {
        Debug.Log("PUN Basics Tutorial/Launcher:OnJoinRandomFailed() was called by PUN. No random room available, so we create one.\nCalling: PhotonNetwork.CreateRoom");
        //base.OnJoinRandomFailed(returnCode, message);
        PhotonNetwork.CreateRoom(null, new RoomOptions());
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("PUN Basics Tutorial/Launcher: OnJoinedRoom() called by PUN. Now this client is in a room.");
        //base.OnJoinedRoom();
    }

    public override void OnDisconnected(DisconnectCause cause)
    {
        Debug.LogWarningFormat("Pub Basics Tutorial/Launcher: OnDisconnected() was called by PUN with reason {0}", cause);
        //base.OnDisconnected(cause);
    }
    #endregion
}

런처에서는 Start에서 Connect메서드를 없애고 버튼을 누를 때마다 Connect를 이벤트로 실행시키도록 했다.

Component에서 이벤트 연동

컴포넌트에서 이벤트를 지정해주었고 버튼을 누르면 Connect가 정상적으로 작동한다.