2

I am a beginner who is trying to make a 2D multiplayer game using Unity, and I found an error that is difficult to solve. I have tried to find a solution but still haven't found it. can you help me? here is my code:

public class PlayerController : MonoBehaviourPun, IPunObservable
{

    public float speed;
    private Rigidbody2D rb2d;
    public Animator animator;

    public PhotonView pv;
    private Vector3 smoothMove;

    private GameObject sceneCamera;
    public GameObject playerCamera;

    // Use this for initialization
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();

        if (photonView.IsMine)
        {
            playerCamera = GameObject.Find("Main Camera").GetComponent<GameObject>();
            //sceneCamera = playerCamera;

            sceneCamera.SetActive(false); // this is line 29
            playerCamera.SetActive(true);
        }
    }
}

this is my code and this error message appears :

NullReferenceException: Object reference not set to an instance of an object PlayerController.Start () (at Assets/Scripts/PlayerController.cs:29)

bguyl
  • 383
  • 3
  • 10
  • your class isn't derived from Monobehaviour instead of it is derived from MonoBehaviourPun, I think it doesn't have Start Function you better check it – Ahmed Ali Jul 28 '20 at 13:20

1 Answers1

1

sceneCamera is never set and it's value is always null because you commented this line :

            //sceneCamera = playerCamera;
  1. You can expose the sceneCamera field to the editor (by making it public for example)
  2. You can find the main scene camera with Camera.main

But you should check if it's null before trying to disable it

public class PlayerController : MonoBehaviourPun, IPunObservable
{

    public float speed;
    private Rigidbody2D rb2d;
    public Animator animator;

    public PhotonView pv;
    private Vector3 smoothMove;

    public GameObject sceneCamera;
    public GameObject playerCamera;

    // Use this for initialization
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();

        if (photonView.IsMine)
        {
            playerCamera = GameObject.Find("Main Camera").GetComponent<GameObject>();

            if (sceneCamera != null)
            {
                sceneCamera.SetActive(false);
            }
            if (playerCamera != null)
            {
                playerCamera.SetActive(true);
            }
        }
    }
}
bguyl
  • 383
  • 3
  • 10