关于局部变量统一的空引用c#

时间:2018-04-03 02:22:59

标签: c# unity3d nullreferenceexception

我在start()方法

中的var参数设置的局部变量上有Null Reference的问题

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using K3DBHandler;

public class Splash : MonoBehaviour {
    private int jmlUser;
    private DataService ds = new DataService("dbK3.sqlite");

    void Start()
    {
       var user = ds.CekUser();
        Hitung(user);
        if (jmlUser == 0)
        {
            StartCoroutine(ToLogin());
        }
        else
        {
            StartCoroutine(ToHome());
        }
    }

  IEnumerator ToHome()
  {
        yield return new WaitForSeconds(5);
        SceneManager.LoadScene("Home");
  }

    IEnumerator ToLogin()
    {
        yield return new WaitForSeconds(5);
        SceneManager.LoadScene("Login");
    }
    private void Hitung(IEnumerable<User> UserCount)
    {
        var c = 0;
        foreach (var a in UserCount)
        {
            c++;
        }
        jmlUser = c;
    }
}

此代码在Unity Editor中运行良好,但是当我将其构建到Android时,我收到如下错误: Null Reference Exception

请帮帮我。

*注意:我使用Unity 2017.3.1f1

1 个答案:

答案 0 :(得分:0)

Unity告诉你,Start方法中的一件事情并不存在。

我已经组织了你的代码,因此检测这个对象会更容易。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using K3DBHandler;

public class Splash : MonoBehaviour {
    private int jmlUser = 0;
    private DataService ds = null;

    void Start()
    {
       ds = new DataService("dbK3.sqlite");
       var user = ds.CekUser();
       Hitung(user);
       if (jmlUser == 0) StartCoroutine(ToLogin());
       else StartCoroutine(ToHome());
    }

    IEnumerator ToHome()
    {
        yield return new WaitForSeconds(5);
        SceneManager.LoadScene("Home");
    }

    IEnumerator ToLogin()
    {
        yield return new WaitForSeconds(5);
        SceneManager.LoadScene("Login");
    }

    private void Hitung(IEnumerable<User> UserCount)
    {
        int c = 0;
        foreach (var a in UserCount) c++;
        jmlUser = c;
    }
}