对象引用未设置为 object.NullReferenceException 的实例:

Object reference not set to an instance of an object.NullReferenceException:

我是初学者,正在尝试使用Unity制作2D多人游戏,我发现了一个难以解决的错误。我试图找到解决方案,但仍未找到。你能帮助我吗? 这是我的代码:

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 并出现此错误消息:

NullReferenceException: 对象引用未设置为对象的实例 PlayerController.Start () (位于 Assets/Scripts/PlayerController.cs:29)

sceneCamera 从未设置,它的值始终是 null 因为您评论了这一行:

            //sceneCamera = playerCamera;
  1. 您可以向编辑器公开 sceneCamera 字段(例如将其设为 public)
  2. 您可以通过Camera.main
  3. 找到主场景相机

但是你应该在尝试禁用它之前检查它是否为 null

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);
            }
        }
    }
}