Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question PlayerPrefs NullReferenceException error

Discussion in 'Scripting' started by cumatru22, Jun 4, 2020.

  1. cumatru22

    cumatru22

    Joined:
    Apr 15, 2020
    Posts:
    5
    It works for the first level, after the level is finished I use it to display the time, but the second and third times does not work. I get "NullReferenceException: Object reference not set to an instance of an object" when I finish the level. Any ideas why?

    [SerializeField]
    private Cronometru VaribileCronometru; // I use this to acces Cronometrule from Cronometru script

    private void OnTriggerEnter(Collider other)
    {
    if (other.gameObject.CompareTag("Pick Up"))
    {
    PlayerPrefs.SetString("YourTime", VaribileCronometru.Cronometrule.text); // here it works
    SceneManager.LoadScene("finishlvl1");
    }
    if (other.gameObject.CompareTag("Pick Up2"))
    {
    PlayerPrefs.SetString("YourTime", VaribileCronometru.Cronometrule.text); // error occurs here
    SceneManager.LoadScene("finishlvl2");
    }
    if (other.gameObject.CompareTag("Pick Up3"))
    {
    PlayerPrefs.SetString("YourTime", VaribileCronometru.Cronometrule.text); // error occurs here
    SceneManager.LoadScene("finishlvl3");
    }
    }
     
    Last edited: Jun 4, 2020
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    When posting code, use code tags.

    When asking for help with an error, be sure to indicate exactly which line the error occurs on.
     
  3. cumatru22

    cumatru22

    Joined:
    Apr 15, 2020
    Posts:
    5
    Thanks! Is my first post here.