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.
  2. Join us on Thursday, June 8, for a Q&A with Unity's Content Pipeline group here on the forum, and on the Unity Discord, and discuss topics around Content Build, Import Workflows, Asset Database, and Addressables!
    Dismiss Notice

Unity Multiplayer [PHOTON] Getting NullReference when theres more players

Discussion in 'Multiplayer' started by Moddwyn, Dec 7, 2017.

  1. Moddwyn


    Jan 27, 2016
    Code (CSharp):
    1. void Start(){
    2.         killFeedUI = GameObject.Find ("KillFeed");
    3.     }
    Code (CSharp):
    1. public void Die(){
    2.         GameObject[] players = GameObject.FindGameObjectsWithTag ("Player");
    3.         foreach(GameObject p in players){
    4.             p.GetComponent <PhotonView>().RPC("SendFeed", PhotonTargets.All, killersName);
    5.         }
    6.         PhotonNetwork.Destroy (gameObject);
    7.     }

    Code (CSharp):
    1. [PunRPC]
    2.     public void SendFeed(string killer){
    3.         GameObject newFeed = GameObject.Instantiate (feedPrefab);
    4.         newFeed.transform.SetParent (killFeedUI.transform);
    5.         newFeed.transform.GetChild (0).GetComponent <Text>().text = (killer + " killed " + GetComponent <PhotonView>().owner.NickName);
    6.         newFeed.transform.localScale = new Vector3 (1, 1, 1);
    7.     }
    In my code above, so bascially when I die, every player will instantiate a UI to their own canvas. Right now, when there's only one player in the room, the SendFeed gets called to that one player(me), everything works fine. But if there's 2 players, I get a nullreference on
    Code (CSharp):
    1. newFeed.transform.SetParent (killFeedUI.transform);
    and the the UI gets instantiated infinately. Why is this happening? Everything works fine with one player, why are there problems with multiple?
  2. tobiass


    Apr 7, 2009
    Debug this some more. You can attach MD or VS to Unity and run this. Both should stop when the nullreference happens and you can look up what value is null. Then think about it why this might be the case.
    It's a game-logic issue more than a network issue.
    Moddwyn likes this.
  3. Munchy2007


    Jun 16, 2013
    It's difficult to say for certain going on the code supplied but you probably want to restrict the SendFeed() function to only run on the local player object.

    Try adding
    Code (CSharp):
    1.  if(!photonView.isMine) return;
    as the first line of your SendFeed() function. (you may want to change the SendFeed() script to inherit from Photon.PunBehaviour if it doesn't already, otherwise you won't have available the handy cached reference to the PhotonView component.
    Moddwyn likes this.