List is removing from two lists when it should only remove from one


I am working on some kind of transition system and I have used two lists. One lists stores the images so they can be reused and one list stores the current images that will be effected. But whenever I call this function the list removes from the list that stores the images and the list that stores the images that will be used. I have no idea why.

Here is some of my code:

public List<GameObject> blackImages = new List<GameObject>();

    public List<GameObject> images = new List<GameObject>();

public void FadeOut()
        images = blackImages;

    IEnumerator FadeOutCo()
        foreach (GameObject image in images)
            image.GetComponent<Image>().color = new Color(image.GetComponent<Image>().color.r, image.GetComponent<Image>().color.g, image.GetComponent<Image>().color.b, 0);

        while(images.Count > 0)
            GameObject imageToRemove = images[Random.Range(0, images.Count)];
            imageToRemove.GetComponent<Image>().color = new Color(imageToRemove.GetComponent<Image>().color.r, imageToRemove.GetComponent<Image>().color.g, imageToRemove.GetComponent<Image>().color.b, 1);
            yield return new WaitForSeconds(delay);

This was quite tricky to explain but I did my best.

Thanks in advance!

As you can see, there is nothing telling it to remove from the blackImages list

Wrong. blackImages is a reference to images, so both lists actually reference the same GameObjects. To create two seperate lists, you need to make sure they hold instances, not references.

c# copy list without reference

When you do this:

images = blackImages;

you’re making images reference of blackImages, in other words it’s one list but two variables pointing to this one list.

So, in your case you may replace the above line to:

images = new List<GameObject>(blackImages);

That way images will store new List with all entries from blackImages.