【问题标题】:Object reference not set to an instance of an object.NullReferenceException: [duplicate]对象引用未设置为对象的实例。NullReferenceException:[重复]
【发布时间】:2020-11-17 21:45:01
【问题描述】:

我是一名初学者,正在尝试使用 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)

【问题讨论】:

  • 你的类不是从 Monobehaviour 派生的,而是从 MonoBehaviourPun 派生的,我认为它没有 Start Function 你最好检查一下

标签: unity3d nullreferenceexception


【解决方案1】:

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

            //sceneCamera = playerCamera;
  1. 您可以将sceneCamera 字段公开给编辑器(例如,将其公开)
  2. 你可以用Camera.main找到主场景相机

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2016-06-05
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多