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

时间:2020-07-28 12:38:26

标签: unity3d nullreferenceexception

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

<table>
  <tr>
    <th class="text-left" style="width:5%">
      <div [style.background-color]="this.user.headercolor">Sno</div>
    </th>
    <th class="text-left" style="width:10%">
      <div [style.background-color]="this.user.headercolor">Date</div>
    </th>
    <th class="text-right" style="width:15%">
      <div [style.background-color]="this.user.headercolor">Amount</div>
    </th>
  </tr>
</table>

{{3}} 并显示此错误消息:

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

1 个答案:

答案 0 :(得分:1)

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

            //sceneCamera = playerCamera;
  1. 您可以向编辑器公开sceneCamera字段(例如,将其公开)
  2. 您可以使用Camera.main
  3. 查找主场景摄像机

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

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);
            }
        }
    }
}
相关问题