using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class FadeInOut : MonoBehaviour
{
List<Material> mats = new List<Material>();
private void Start()
{
foreach (Transform g in transform.GetComponentsInChildren<Transform>())
{
if (g.GetComponent<SkinnedMeshRenderer>() != null)
{
var l = g.GetComponent<SkinnedMeshRenderer>().sharedMaterials.ToList();
foreach(Material mat in l)
{
mats.Add(mat);
}
}
}
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.G))
{
StartCoroutine(FadeToTogether(mats, 0, 0.5f));
}
}
IEnumerator FadeTo(List<Material> materials, float targetOpacity, float duration)
{
for (int i = 0; i < materials.Count; i++)
{
Color color = materials[i].color;
float startOpacity = color.a;
float t = 0;
while (t < duration)
{
t += Time.deltaTime;
float blend = Mathf.Clamp01(t / duration);
color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);
materials[i].color = color;
yield return null;
}
}
}
IEnumerator FadeToTogether(List<Material> materials, float targetOpacity, float duration)
{
float t = 0;
List<float> startOpacities = new List<float>();
foreach (var material in materials)
{
startOpacities.Add(material.color.a);
}
while (t < duration)
{
t += Time.deltaTime;
float blend = Mathf.Clamp01(t / duration);
for (int i = 0; i < materials.Count; i++)
{
Color color = materials[i].color;
color.a = Mathf.Lerp(startOpacities[i], targetOpacity, blend);
materials[i].color = color;
}
yield return null;
}
yield return new WaitForSeconds(0.1f);
if (targetOpacity == 0)
{
StartCoroutine(FadeToTogether(mats, 1, 0.5f));
}
else
{
StartCoroutine(FadeToTogether(mats, 0, 0.5f));
}
}
}
All the materials rendering mode are set to Fade.
The problem is when i stop the game the alpha color stay in the editor at the value when i stopped the game so the character/object with the materials sometimes is half faded out or sometimes faded out completely.
Is there a way to make that when i stop the game it will set the materials alpha color to 1?
I tried to add this to the bottom of the script but it's not doing anything :
private void OnApplicationQuit()
{
StartCoroutine(FadeToTogether(mats, 1, 0));
}