Help I do not know how to change the color of the player gradually on collision to any object. I wrote a script and applied it to the player but it of course does what is say, but is limited to it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
GetComponent<SpriteRenderer>().color = new Color(255f, 255f, 255f, 0f); //Code works
Debug.Log("Collision"); //Collision is true
}
}
So, how do I make the alpha value (0f) decrease from 255 to 0 in 1-2 seconds?
How do I build up the code?
Thanks in advance
So first off, let me just note that Color in Unity works a bit differently than you are expecting. The values in Color range from 0 to 1, not 0 to 255. (If you really prefer 0 to 255, there is a separate type you can use called Color32 which is effectively interchangeable with Color. Unity - Scripting API: Color32).
Now that’s out of the way, this is a perfect use case for a Coroutine using Color.Lerp:
public class test : MonoBehaviour {
private void OnCollisionEnter2D(Collision2D collision) {
Debug.Log("Collision"); //Collision is true
StartCoroutine(FadeAlphaToZero(GetComponent<SpriteRenderer>(), 2f));
}
IEnumerator FadeAlphaToZero(SpriteRenderer renderer, float duration) {
Color startColor = renderer.color;
Color endColor = new Color(startColor.r, startColor.g, startColor.b, 0);
float time = 0;
while (time < duration) {
time += Time.deltaTime;
renderer.color = Color.Lerp(startColor, endColor, time/duration);
yield return null;
}
}
}
The coroutine will run every frame for the duration you give it, and it will gradually fade the alpha value of your sprite to 0 from wherever it started.
Works like a charm. Thank you very much (^∇^)
I literary can imagine going through this searching the documentation for weeks, thinking code, watching tutorials. Phew, thank you once again.