Color Changing Breaks after removing items from list

Hi there! I am currently running a script that changes the colors of my level, designed for identifying new sprites that are being created by my spawner script.

The thing is that now, due to performance issues, I need to implement something so that I can destroy the level parts that are not visible anymore and not needed, as they gather up and eat up a ton of resources after a while.

I tried to test things a bit and added a function that removes missing sprites.I deleted a few of the clones via the inspector just to test things and it seems that it throws some errors

Here’s what I’m doing currently and what I tried :

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;
public class Level_ColorChanger : MonoBehaviour
{
    //How fast do we change
    public float ChangeTime = 2f;
    //How long do we wait before changing again
    public List<SpriteRenderer> _spriteRenderers;

    float r;
    float g;
    float b;

    private Image background;
    public float WaitTime = 3f;



    void Start()
    {
        //Make a new List
        _spriteRenderers = new List<SpriteRenderer>();
        //Find our renderers
        background = GameObject.FindGameObjectWithTag("ColoredPart_Background").GetComponent<Image>();


        StartCoroutine(ChangeColor());
    }
 
    public void SearchSprites()
    {
        var sprites = GameObject.FindGameObjectsWithTag("ColoredPart_Level");
        for (var i = 0; i < sprites.Length; i++)
        {
            //See if it has a renderer on it
            var renderer = sprites[i].GetComponent<SpriteRenderer>();
            //Add it to the list if it does
            if (!_spriteRenderers.Contains(renderer))
            {
                _spriteRenderers.Add(renderer);
            }
        }
    }

    void SearchForMissingSprites()
    {
        for (int i = _spriteRenderers.Count - 1; i >= 0; i--)
        {
            if (_spriteRenderers[i] = null)
            {
                _spriteRenderers.RemoveAt(i);
            }
        }
    }


    private void Update()
    {
        SearchForMissingSprites();
    }

            while (t <= 1)
            {
                var bgstartColour = new Color(1, 1, 1);
                background.color = Color.Lerp(bgstartColour, bgColor, t);
                for (int i = 0; i < count; i++)
                {
                    var startColour = _spriteRenderers[i].color;
/* I'm getting the
 NullReferenceException : Object reference not set to an instance of an object over here at the
 startColour
*/
                    var lerpedColour = Color.Lerp(startColour, newColor, t);
                    _spriteRenderers[i].color = lerpedColour;
                }
                //Update our t according to how much time has passed
                t += Time.deltaTime / ChangeTime;
                yield return null;
            }

}

Feel free to use this in your projects if this is what you need!

I commented on the line where I get a nullReference exception and I don’t know why I’m getting it, because if I remove the SearchForMissingSprites function, everything functions properly.It breaks absolutely everything, My sprite renderers list gets updated but adds empty elements ( None (Sprite Renderer) ).What is happening over here?

So, the real question is, how would I go about updating the list of sprite renderers so that my color changing doesn’t break?Because obviously if I just destroy the previous parts, the color changing still breaks.I’m guessing that what is wrong here is the way I am removing the sprites from the list and the fact that maybe I’m deleting them from the inspector instead of actually destroying them via a script?

Further explanation of the solution would be greatly appreciated as I’m still learning!

Thank you for the help! :slight_smile:

One error is here:
if (_spriteRenderers *= null)*
You’re assigning null instead of checking.
Another potential error is here:
```csharp

  •        //See if it has a renderer on it
          var renderer = sprites[i].GetComponent<SpriteRenderer>();
          //Add it to the list if it does*
    

```
You’re adding it even if it doesn’t has SpriteRenderer… Because tag does not guarantee that gameobject has this specific component… this is within human error range.
Check it for null and add only if it’s not.

1 Like