Evorlor
Evorlor

Reputation: 7568

Why can I not change the Sprite attribute directly?

I accidentally cross posted when I tried to switch the site I was posting to. Oops! https://gamedev.stackexchange.com/questions/120309/why-can-i-not-change-a-sprite-directly/120311#120311


I am changing the Sprites on an array of Images. I could think of two ways to go about it. The first way being:

var images = GetComponentsInChildren<Image>();
foreach(var image in images)
{
    if (!image.sprite)
    {
        image.sprite = GetMySprite();
    }
}

This way works perfectly. But if I try to grab the sprite itself like so:

var images = GetComponentsInChildren<Image>();
foreach(var image in images)
{
    var sprite = image.sprite;
    if (!sprite)
    {
        sprite = GetMySprite();
    }
}

It does not work. The Sprite gets assigned, but it is not the original Sprite. The Sprite attached to the Image remains null.

At first I thought, maybe Sprite is a struct? But it is not - it is a sealed class extending Object. (And I don't think that would necessarily explain it anyways).

So why must I retain the reference to the Image when changing its Sprite attribute?

Upvotes: 0

Views: 60

Answers (1)

PaulF
PaulF

Reputation: 6773

In both instances the sprite field is a reference to a sprite object. In your second example you create a local variable which is also a reference to a sprite object - that you initialise by copying the value from image.sprite. Note that "var sprite" is not a reference to "image.sprite" itself.

In the second example, you only modify the value of the local variable, leaving the original unchanged.

Upvotes: 2

Related Questions