0

I have renamed the Classes and simplified the content for this post. Both level2 and spriteRenderer are visible in the inspector after hitting start, but spriteRenderer doesn't seem to be loaded when the fill method is called. After checking with Debug.Log(spriteRenderer==null);, it is false when used after AddComponent in the Start() of Level2, but true when called in fill().

Level1 Class:

class Level1:MonoBehaviour{
  Level2 level2;
  void Start(){
    level2 = this.AddComponent<Level2>();
    level2.enabled = true;
    level2.fill(Color.red); //nullReference
  }
}

Level2 Class:

class Level2:MonoBehaviour{
  SpriteRenderer spriteRenderer;
  void Start(){
    spriteRenderer = this.AddComponent<SpriteRenderer>();
    spriteRenderer.enabled = true;
    //spriteRenderer!=null
  }
  
  public void fill(Color color){
    Texture2D texture = new Texture2D(16, 16);
    texture.filterMode = FilterMode.Point;
    for (int y = 0; y < 16; y++)
    {
      for (int x = 0; x < 16; x++)
      {
                texture.SetPixel(x, y, color);
      }
    }
    texture.Apply();
    Rect rect = new Rect(new Vector2(0.0f, 0.0f), new Vector2(16, 16));
    //spriteRenderer==null
    spriteRenderer.sprite = Sprite.Create(texture, rect, Vector2.zero, 8);//nullReference
  }
}

Tried to access generated spriteRenderer, which is added in Start() of a MonoBehaviour-Class, through another method from the same class. The MonoBehaviour-class is added inside of another MonoBehaviour-Class on Start and the fill-Method is also called afterwards.

  • 4
    The issue you're facing is because you are trying to access the `spriteRenderer` variable in the `fill()` method before it has been assigned a value in the `Start()` method of the `Level2` class.To fix this issue, you can use the `Awake()` method instead of `Start()` in the `Level2` class to ensure that the `spriteRenderer` variable is initialized before it is accessed in the `fill()` method. – Nima Jul 08 '23 at 14:04

0 Answers0