Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question How can I find and access Local player components using PUN2 in Unity?

Discussion in 'Multiplayer' started by BhsGamez, Feb 15, 2023.

  1. BhsGamez

    BhsGamez

    Joined:
    Jan 22, 2018
    Posts:
    7
    Hello,

    I have 2 scripts 1: Player and 2: Game Manager, both spawn when the game starts.
    Since each player will be spawning the same 2 objects (player and game manager) when the game starts, How can I access the local Player script from Game Manager Start function when the game starts?

    I tried this method:
    Code (CSharp):
    1. GameObject[] players;
    2. GameObject localPlayer;
    3.  
    4. void Start()
    5. {
    6.     if(pv.IsMine)
    7.     {
    8.         players = GameObject.FindGameObjectsWithTag("Player");
    9.         foreach (GameObject local in players)
    10.         {
    11.            if(local.GetPhotonView().IsMine)
    12.            {
    13.                localPlayer = local.gameObject;
    14.                Debug.Log("Local Player: " + localPlayer.name);
    15.            }
    16.         }
    17.     }
    18. }
    But it sometimes works and sometimes returns Null Reference error and breaks my game.

    However if I try this one:
    if(pv.IsMine){ localPlayer = GameObject.FindGameObjectWithTag("Player"); }

    It produces less Null Reference error as compared to the above code, but still its not the solution.
    How can I fix this issue or is there a better way to access the local player?