Search Unity

NullReferenceException thrown even when variable is assigned

Discussion in 'Scripting' started by MiaoBolverk, Jul 31, 2018.

  1. MiaoBolverk

    MiaoBolverk

    Joined:
    Feb 6, 2018
    Posts:
    26
    Here are the relevant code snippets:
    Code (csharp):
    1.  
    2.     private Renderer meshRenderer;
    3.  
    4.     private void Awake()
    5.     {
    6.         this.meshRenderer = this.gameObject.GetComponent<Renderer>();
    7.     }
    8.  
    9.     private void Update()
    10.     {
    11.         this.meshRenderer.enabled = /* Check some condition */
    12.     }
    Stepping through the code in debug mode, I can see that this.meshRenderer is assigned in the Awake() method.

    However, when the Update() method is called, a NullReferenceException error is thrown, claiming that this.meshRenderer is null.

    The only explanation I can think of for this behaviour is that this.meshRenderer is nullified somehow after the Awake() method is called, but I don't know why or how.

    None of my MonoBehaviour scripts implements the Start() method.

    Any advice?
     
  2. FlashMuller

    FlashMuller

    Joined:
    Sep 25, 2013
    Posts:
    451
    Never Mind, sorry