Kali
Kali

Reputation: 5

Color switching in Unity (with script)

I want to increase alpha channel on every hit taken by an object. But i cant use my Alpha variable as it's an integer and color32 needs byte value. I know about color, which is float, but it's not working for me, I need color32. How can i do that?

void OnCollisionEnter2D (Collision2D col) {

        Alpha += 255 / maxHits;
        currentHit++;
        gameObject.GetComponent<SpriteRenderer> ().color = new Color32(159,86,86,Alpha);
        if (currentHit == maxHits) {
            Destroy (gameObject);
        }
}

Upvotes: 0

Views: 726

Answers (2)

Daahrien
Daahrien

Reputation: 10320

Make sure Alpha is a float. try this:

float Alpha = 0;

void OnCollisionEnter2D (Collision2D col) {

        Alpha += 1f / maxHits;
        currentHit++;
        gameObject.GetComponent<SpriteRenderer> ().color = new Color(159f/255,86f/255,86f/255,Alpha);
        if (currentHit == maxHits) {
            Destroy (gameObject);
        }
}

Upvotes: 1

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

It's very meaningfull that you can only plug in alpha values which are a byte, i.e. between 0 and 255. That's because the used color system (24 bit RGBA) has exactly 8 bits/1 byte per color channel. It doesn't make sense to try and plug in values above 255 or below 0.

When you can make sure that your Alpha variable has meaningful values between 0 and 255, just cast it to a byte by prepending (byte) in front of it, or directly declare Alpha to be of type byte. That's it.

Upvotes: 0

Related Questions