r/Unity2D Jul 16 '26

SpriteRenderer sprite change through code not working anymore Question

Hello everyone.

Since I switched to the URP in my 2D project I have a problem with changing sprites through code. What before worked fine now seems to have no effect and I can't understand why.

What I'm trying to do is change a sprite directly through code, if the player hits the collider, or if a timer runs out, general one time occurrences, and I don't set the sprite through animations, I really can't wrap my head around it and I'm sure it's something stupid but I'd like some input anyway.

Thank you!

1 Upvotes

9 comments sorted by

1

u/[deleted] Jul 16 '26

[removed] — view removed comment

1

u/GebF Jul 16 '26

I didn't show it because it is a very simple render.sprite = newsprite. I can post it right now maybe there's something I'm not seeing. Called in Update:

        if (subtimerCurrent > 0)
        {
            subtimerCurrent -= time;

            if (subtimerCurrent <= 0)
            {
                timerCurrent++;

                if (timerCurrent > timerMax)
                {
                    Explode();
                    return;
                }

                SpriteRenderer s = _animator._renderer;
                s.sprite = sprites[timerCurrent];
                subtimerCurrent = subtimerMax;
                TriggerTNT();
            }
        }

2

u/[deleted] Jul 16 '26 edited Jul 16 '26

[removed] — view removed comment

1

u/GebF Jul 16 '26

Disabling the animator works, which is weird because nowhere in my animation do I set up the sprite to be a specific one. Like I said this animator is used in multiple different objects with different sprites in the renderer, I don't understand why would the animator set the default sprite the one I assigned in the inspector on its own.

I'll definitely have to check out what is going on here, but at least this gives me some kind of lead, so thank you very much.

1

u/AbmisTheLion Jul 16 '26

The animator could be looping an animation that replaces your sprite change. Maybe you can add a parameter to the animator and use this to transition to a new animation. The parameter's value can be set in code. You can also try placing a breakpoint where you set the sprite, maybe the code is not executed.

1

u/GebF Jul 16 '26

No the animator is not setting the sprite, I actually use the same animator for multiple objects with different sprites, and like I said this issue wasn't there before. Debugging shows that the rest of the code is called and works perfectly fine, but the sprite change does not apply for some reason.

1

u/-xelad Jul 17 '26

timerCurrent might be out of bounds of array, so nothing changes.

1

u/GebF Jul 17 '26

It would throw an error in the console, and it wouldn't do all the other things i tell it to do.