Home > Software engineering >  Spawn players in different positions Unity Photon
Spawn players in different positions Unity Photon

Time:08-12

I'm trying to spawn players in different positions. I use RPC for this, the players will spawn in different positions, as I want, BUT this method additionally duplicates (to be more precise, it will spawn copies of the player depending on the total number of all players) of the player, how can this be fixed? Maybe there is some kind of test for this? Or a better way? If you add break after i , then only the Master player and his copies will be saved.

public class PlayerManager : MonoBehaviour
{
    private PhotonView _photonView;
 
    private void Start()
    {
        _photonView = GetComponent<PhotonView>();
 
        if (_photonView.IsMine)
        {
            int i = 0;
            foreach (var p in PhotonNetwork.PlayerList)
            {
                _photonView.RPC(nameof(CreateController), p, i);
                i  ;
            }
        }
    }
 
    [PunRPC]
    private void CreateController(int i)
    {
        var playerAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Player"), GameManager.instance.spawnPoints[i].position, Quaternion.identity);
    }
}

CodePudding user response:

Your CreateController RPC is called by each client, leading to n^2 player instances being created. Use photonView.IsMasterClient in the Start method, instead of photonView.IsMine

For an even better solution that doesn't require the host to call RPCs, you can use Array.IndexOf(PhotonNetwork.PlayerList, PhotonNetwork.LocalPlayer) to get that same i number. That way you can just put the instantiate in the Start method;

//Change to extending MonoBehaviourPun and you get a "photonView" variable for free
public class PlayerManager : MonoBehaviourPun
{
    //private PhotonView _photonView;
 
    private void Start()
    {
        int i = Array.IndexOf(PhotonNetwork.PlayerList, PhotonNetwork.LocalPlayer);
        var playerAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Player"), GameManager.instance.spawnPoints[i].position, Quaternion.identity);
    }
}
  • Related