Search Unity

  1. Unity 2019.2 is now released.
    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:
    349
    If you use MEC you might yield return 0. If you use Unity's default coroutines you probably want to return null.