0
\$\begingroup\$

Whenever I add colors in Unity using script it updates it in the sprite renderer but I don't see the result on screen and it's not the alpha issue. I can see the result in the sprite renderer color tab, so if I pause the game and click on the color panel it changes it.

Color color = collision.gameObject.GetComponent<SpriteRenderer>().color;
       
sr.color += color;

This is what I am doing. It updates the color successfully in inspector but doesn't in playmode.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I'm unable to reproduce this issue. Using the following script:

public class CollisionColor : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D other) {
        if (other.collider.TryGetComponent(out SpriteRenderer otherSR)) {
            GetComponent<SpriteRenderer>().color += otherSR.color;
        }
    }
}

And this sprite setup:

Inspector setup of sprite

I find the sprites change colour in play mode when they collide, as expected:

Animation of coloured balls changing colours on collision

So, the problem is somewhere in code you have not shown us. Double-check that the object you're inspecting is the one you're seeing on screen, and that your sr variable is referring to the SpriteRenderer you expect. A common error here is to keep holding onto a reference to the prefab the objects were spawned from, rather than the live copy running in the scene.

If you're unable to identify the cause, then edit your question to include a Minimal Complete Verifiable Example: every line of code and every step of scene/inspector setup that a reader would need to follow, starting from a new, empty project, to reproduce the same problem you're seeing. Once we can reproduce the issue, we can test potential fixes to be sure they'll work for you.

\$\endgroup\$
2
  • \$\begingroup\$ It works for me too when my object starting color is not white. Try with white color. \$\endgroup\$
    – Nomi
    Oct 28, 2022 at 12:24
  • \$\begingroup\$ @Nomi that's what you'd expect with += though, isn't it? When you're adding colour values without subtracting/multiplying/dividing anywhere you can only make the colours brighter. Once you're at white (1, 1, 1) there's nowhere brighter to go. Adding any other value just makes the numbers larger than the colour range of 0-1, so they get clamped back to 1 again. Did you perhaps mean to average your colours rather than add them? Or did you have some other colour combination operation in mind? You may want to post a new question about that. \$\endgroup\$
    – DMGregory
    Oct 28, 2022 at 13:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .