Giant vs Human 팀프로젝트 개발일지

[Giant vs Human 팀프로젝트] Photon 멀티 동기화

다모아 2023. 11. 30. 17:49

Player 프리팹

 

 

 

 

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

public class GameMain : MonoBehaviour
{
    [SerializeField] private List<GameObject> prefabs;
    private int cnt = 0;

    // Start is called before the first frame update
    void Start()
    {
        var pool = PhotonNetwork.PrefabPool as DefaultPool;
        foreach (GameObject prefab in this.prefabs)
        {
            pool.ResourceCache.Add(prefab.name, prefab);
        }
        PhotonManager.instance.Connect(() =>
        {   
            this.CreatePlayer();          
        });
    }

    private void CreatePlayer()
    {
        Transform[] points = GameObject.Find("SpawnPointGroup").GetComponentsInChildren<Transform>();
        int idx = Random.Range(1, points.Length);   // 1 ~ 3
        Transform initPoint = points[idx];

        if (PhotonNetwork.IsMasterClient)
        {
            PhotonNetwork.Instantiate("NetworkRig", Vector3.zero, Quaternion.identity);
        }
        else
        {
            PhotonNetwork.Instantiate("Player", initPoint.position, initPoint.rotation);
        }
               
        Debug.Log("플레이어가 생성되었습니다.");
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using System;

public class PhotonManager : MonoBehaviourPunCallbacks
{

    private readonly string version = "1.0.0";
    public static PhotonManager instance;  //싱글톤
    public string nickname;
     
    public Action onJoinedRoomAction;

    private void Awake()
    {
        PhotonManager.instance = this;
    }

    public void Connect(Action onJoinedRoomCallback)
    {
        this.onJoinedRoomAction = onJoinedRoomCallback;

        PhotonNetwork.AutomaticallySyncScene = true;
        PhotonNetwork.GameVersion = version;
        PhotonNetwork.NickName = this.nickname;
        PhotonNetwork.ConnectUsingSettings();
    }

    public override void OnConnectedToMaster()
    {
        Debug.Log("마스터 서버 접속 됨");
        PhotonNetwork.JoinLobby();
    }

    public override void OnJoinedLobby()
    {
        Debug.Log("로비에 접속됨");
        PhotonNetwork.JoinRandomOrCreateRoom();
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("룸에 입장");
        this.onJoinedRoomAction();
    }

    public override void OnCreateRoomFailed(short returnCode, string message)
    {
        Debug.Log("룸 생성 실패 : " + message);
    }

    public override void OnJoinRandomFailed(short returnCode, string message)
    {
        Debug.Log("룸 입장 실패 : " + message);
    }

    public override void OnPlayerEnteredRoom(Player newPlayer)
    {
        Debug.LogFormat("{0}님이 룸에 입장", newPlayer.NickName);
    }
}