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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

NullReferenceException: Object reference not set, Help!

Discussion in 'Scripting' started by gringofxs, Feb 8, 2017.

  1. gringofxs

    gringofxs

    Joined:
    Oct 14, 2012
    Posts:
    240
    i have error on this script, how can i fix it.
    NullReferenceException: Object reference not set to an instance of an object
    LoadImage.Update () (at Assets/LoadImage.cs:25) is this line: if (!imgLink.isDone)

    Code (CSharp):
    1. usingUnityEngine;
    2. usingUnityEngine.UI;
    3. usingSystem.Collections;
    4.  
    5. [ExecuteInEditMode]
    6.  
    7. publicclassLoadImage: MonoBehaviour
    8. {
    9. stringurl = "http://nfx.000webhostapp.com/gazin.jpg";
    10. Texture2Dimg;
    11.  
    12. publicSpriteRendererspriteRenderer;
    13. publicImageFilling;
    14. publicGameObjectLoading;
    15. WWWimgLink;
    16. //Usethisforinitialization
    17. voidStart()
    18. {
    19. spriteRenderer.sprite = null;
    20. StartCoroutine(LoadImg());
    21.  
    22. }
    23. voidUpdate ()
    24. {
    25. if (!imgLink.isDone)
    26. Filling.fillAmount = imgLink.progress;
    27. }
    28. IEnumeratorLoadImg()
    29. {
    30. yieldreturn0;
    31. //spriteRenderer.sprite = null;
    32. imgLink = newWWW(url);
    33. yieldreturnimgLink;
    34.  
    35. img = imgLink.texture;
    36. Spritesprite = Sprite.Create(img, newRect(0, 0, img.width, img.height), newVector2(0.5f, 0.5f));
    37. spriteRenderer.sprite = sprite;
    38. Loading.SetActive (false);
    39.  
    40. }
    41.  
    42. voidOnGUI()
    43. {
    44. }
    45. }
     
    Last edited: Feb 8, 2017
  2. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Plase use Code Tags when posting code and make sure it's formatted correctly.

    As for your problem. You call the WWW on the coroutine after a yield return 0; (Which I assume is the same as yield return null??), which means it will be called after Update in the first frame. So at the first frame the field imgLink will be null.
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Timelog likes this.
  4. gringofxs

    gringofxs

    Joined:
    Oct 14, 2012
    Posts:
    240
    Thank you, it works great.
     
  5. Trinary

    Trinary

    Joined:
    Jul 26, 2013
    Posts:
    395
    If you use MEC you might yield return 0. If you use Unity's default coroutines you probably want to return null.